<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>6 Object Relational Mapping (GORM) 2.2.1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link rel="stylesheet" href="../css/main.css" type="text/css" media="screen, print" title="Style" charset="utf-8"/>
    <link rel="stylesheet" href="../css/pdf.css" type="text/css" media="print" title="PDF" charset="utf-8"/>
    <script type="text/javascript">
function addJsClass() {
    var classes = document.body.className.split(" ");
    classes.push("js");
    document.body.className = classes.join(" ");
}
    </script>
</head>

<body class="body" onload="addJsClass();">
<div id="navigation">
    <ul>
        <li>
            <div id="nav-summary" onmouseover="toggleNavSummary(false)" onmouseout="toggleNavSummary(true)">
                <a href="../guide/index.html" class="button">Table of contents</a>

                <div id="nav-summary-childs" style="display:none;">
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/introduction.html"><strong>1</strong><span>Introduction</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/gettingStarted.html"><strong>2</strong><span>Getting Started</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/upgradingFromPreviousVersionsOfGrails.html"><strong>3</strong><span>Upgrading from previous versions of Grails</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/conf.html"><strong>4</strong><span>Configuration</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/commandLine.html"><strong>5</strong><span>The Command Line</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/GORM.html"><strong>6</strong><span>Object Relational Mapping (GORM)</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/theWebLayer.html"><strong>7</strong><span>The Web Layer</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/validation.html"><strong>8</strong><span>Validation</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/services.html"><strong>9</strong><span>The Service Layer</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/testing.html"><strong>10</strong><span>Testing</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/i18n.html"><strong>11</strong><span>Internationalization</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/security.html"><strong>12</strong><span>Security</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/plugins.html"><strong>13</strong><span>Plugins</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/webServices.html"><strong>14</strong><span>Web Services</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/spring.html"><strong>15</strong><span>Grails and Spring</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/hibernate.html"><strong>16</strong><span>Grails and Hibernate</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/scaffolding.html"><strong>17</strong><span>Scaffolding</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/deployment.html"><strong>18</strong><span>Deployment</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0"><a href="../guide/contributing.html"><strong>19</strong><span>Contributing to Grails</span></a>
                    </div>
                    
                </div>
            </div>
        </li>
        <li class="separator selected">
            <a id="ref-button" onclick="localToggle(); return false;" href="#">Quick Reference</a>
        </li>
    </ul>
</div>
<div id="header">
    <div class="images clearfix">
        
        <span id="logo"><a href="http://grails.org" target="_blank"><img alt="Grails Logo" title="The Grails Framework" src="../img/grails.png" border="0"/></a></span>
        
        
        <span id="sponsor"><a href="http://springsource.com" target="_blank"><img alt="SpringSource Logo" title="SpringSource - Weapons for the War on Java Complexity" src="../img/springsource-logo.png" border="0"/></a></span>
        
    </div>
    <p>See the light - agile, industrial strength, rapid web application development made easy</p>
</div>


<table id="colset" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td id="col1">
            <div id="main" class="corner-all">

                
                    <div class="toc-item prev-left"><a href="../guide/commandLine.html">&lt;&lt; <strong>5</strong><span>The Command Line</span></a></div>
                

                <span id='toggle-col1' class="toggle">(<a href="#" onclick="localToggle(); return false;">Quick Reference</a>)</span>

                
                    <div class="toc-item next-right"><a href="../guide/theWebLayer.html"><strong>7</strong><span>The Web Layer</span> >></a></div>
                


                <div class="project">
                    <h1>6 Object Relational Mapping (GORM) - Reference Documentation</h1>

                    <p><strong>Authors:</strong> Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith</p>

                    <p><strong>Version:</strong> 2.2.1</p>

                    
                </div>

                
                <div id="table-of-content">
                    <h2>Table of Contents</h2>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#quickStartGuide"><strong>6.1</strong><span>Quick Start Guide</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#basicCRUD"><strong>6.1.1</strong><span>Basic CRUD</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#domainClasses"><strong>6.2</strong><span>Domain Modelling in GORM</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#gormAssociation"><strong>6.2.1</strong><span>Association in GORM</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#manyToOneAndOneToOne"><strong>6.2.1.1</strong><span>Many-to-one and one-to-one</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#oneToMany"><strong>6.2.1.2</strong><span>One-to-many</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#manyToMany"><strong>6.2.1.3</strong><span>Many-to-many</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#basicCollectionTypes"><strong>6.2.1.4</strong><span>Basic Collection Types</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#gormComposition"><strong>6.2.2</strong><span>Composition in GORM</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#inheritanceInGORM"><strong>6.2.3</strong><span>Inheritance in GORM</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#sets,ListsAndMaps"><strong>6.2.4</strong><span>Sets, Lists and Maps</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#persistenceBasics"><strong>6.3</strong><span>Persistence Basics</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#savingAndUpdating"><strong>6.3.1</strong><span>Saving and Updating</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#deletingObjects"><strong>6.3.2</strong><span>Deleting Objects</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#cascades"><strong>6.3.3</strong><span>Understanding Cascading Updates and Deletes</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#fetching"><strong>6.3.4</strong><span>Eager and Lazy Fetching</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#locking"><strong>6.3.5</strong><span>Pessimistic and Optimistic Locking</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#modificationChecking"><strong>6.3.6</strong><span>Modification Checking</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#querying"><strong>6.4</strong><span>Querying with GORM</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#finders"><strong>6.4.1</strong><span>Dynamic Finders</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#whereQueries"><strong>6.4.2</strong><span>Where Queries</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#criteria"><strong>6.4.3</strong><span>Criteria</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#detachedCriteria"><strong>6.4.4</strong><span>Detached Criteria</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#hql"><strong>6.4.5</strong><span>Hibernate Query Language (HQL)</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#advancedGORMFeatures"><strong>6.5</strong><span>Advanced GORM Features</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#eventsAutoTimestamping"><strong>6.5.1</strong><span>Events and Auto Timestamping</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#ormdsl"><strong>6.5.2</strong><span>Custom ORM Mapping</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#tableAndColumnNames"><strong>6.5.2.1</strong><span>Table and Column Names</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#caching"><strong>6.5.2.2</strong><span>Caching Strategy</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#inheritanceStrategies"><strong>6.5.2.3</strong><span>Inheritance Strategies</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#identity"><strong>6.5.2.4</strong><span>Custom Database Identity</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#compositePrimaryKeys"><strong>6.5.2.5</strong><span>Composite Primary Keys</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#databaseIndices"><strong>6.5.2.6</strong><span>Database Indices</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#optimisticLockingAndVersioning"><strong>6.5.2.7</strong><span>Optimistic Locking and Versioning</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#fetchingDSL"><strong>6.5.2.8</strong><span>Eager and Lazy Fetching</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#customCascadeBehaviour"><strong>6.5.2.9</strong><span>Custom Cascade Behaviour</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#customHibernateTypes"><strong>6.5.2.10</strong><span>Custom Hibernate Types</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#derivedProperties"><strong>6.5.2.11</strong><span>Derived Properties</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:20px"><a href="#customNamingStrategy"><strong>6.5.2.12</strong><span>Custom Naming Strategy</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:10px"><a href="#defaultSortOrder"><strong>6.5.3</strong><span>Default Sort Order</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#programmaticTransactions"><strong>6.6</strong><span>Programmatic Transactions</span></a>
                    </div>
                    
                    <div class="toc-item" style="margin-left:0px"><a href="#gormConstraints"><strong>6.7</strong><span>GORM and Constraints</span></a>
                    </div>
                    
                </div>
                

                
<a name="5. Object Relational Mapping (GORM)"><!-- Legacy link --></a>
<h1 id="GORM">6 Object Relational Mapping (GORM)</h1>
Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships; one-to-one, one-to-many, or many-to-many.<p class="paragraph"/>GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (a very popular and flexible open source ORM solution) and thanks to the dynamic nature of Groovy with its static and dynamic typing, along with the convention of Grails, there is far less configuration involved in creating Grails domain classes.<p class="paragraph"/>You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java&#45;quote">"Groovy in Action"</span>)<p class="paragraph"/>book
  .addToAuthors(name:<span class="java&#45;quote">"Dierk Koenig"</span>)
  .addToAuthors(name:<span class="java&#45;quote">"Guillaume LaForge"</span>)
  .save()</pre></div>


<a name="5.1 Quick Start Guide"><!-- Legacy link --></a>
<h2 id="quickStartGuide">6.1 Quick Start Guide</h2>
A domain class can be created with the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> command:<p class="paragraph"/><div class="code"><pre>grails create&#45;domain&#45;class helloworld.Person</pre></div><p class="paragraph"/><blockquote class="note">
If no package is specified with the create-domain-class script, Grails automatically uses the application name as the package name.
</blockquote><p class="paragraph"/>This will create a class at the location <code>grails-app/domain/helloworld/Person.groovy</code> such as the one below:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">package</span> helloworld<p class="paragraph"/>class Person &#123;
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
If you have the <code>dbCreate</code> property set to "update", "create" or "create-drop" on your <a href="../guide/single.html#dataSource" class="guide">DataSource</a>, Grails will automatically generate/modify the database tables for you.
</blockquote><p class="paragraph"/>You can customize the class by adding properties:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    <span class="java&#45;object">String</span> name
    <span class="java&#45;object">Integer</span> age
    Date lastVisit
&#125;</pre></div><p class="paragraph"/>Once you have a domain class try and manipulate it with the <a href="../ref/Command Line/shell.html" class="commandLine">shell</a> or <a href="../ref/Command Line/console.html" class="commandLine">console</a> by typing:<p class="paragraph"/><div class="code"><pre>grails console</pre></div><p class="paragraph"/>This loads an interactive GUI where you can run Groovy commands with access to the Spring ApplicationContext, GORM, etc.


<a name="5.1.1 Basic CRUD"><!-- Legacy link --></a>
<h2 id="basicCRUD">6.1.1 Basic CRUD</h2>
Try performing some basic CRUD (Create/Read/Update/Delete) operations.<p class="paragraph"/><h4>Create</h4><p class="paragraph"/>To create a domain class use Map constructor to set its properties and call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a>:<p class="paragraph"/><div class="code"><pre>def p = <span class="java&#45;keyword">new</span> Person(name: <span class="java&#45;quote">"Fred"</span>, age: 40, lastVisit: <span class="java&#45;keyword">new</span> Date())
p.save()</pre></div><p class="paragraph"/>The <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method will persist your class to the database using the underlying Hibernate ORM layer.<p class="paragraph"/><h4>Read</h4><p class="paragraph"/>Grails transparently adds an implicit <code>id</code> property to your domain class which you can use for retrieval:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
assert 1 == p.id</pre></div><p class="paragraph"/>This uses the <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> method that expects a database identifier to read the <code>Person</code> object back from the database.
You can also load an object in a read-only state by using the <a href="../ref/Domain Classes/read.html" class="domainClasses">read</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.read(1)</pre></div><p class="paragraph"/>In this case the underlying Hibernate engine will not do any dirty checking and the object will not be persisted. Note that
if you explicitly call the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method then the object is placed back into a read-write state.<p class="paragraph"/>In addition, you can also load a proxy for an instance by using the <a href="../ref/Domain Classes/load.html" class="domainClasses">load</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.load(1)</pre></div><p class="paragraph"/>This incurs no database access until a method other than getId() is called. Hibernate then initializes the proxied instance, or
throws an exception if no record is found for the specified id.<p class="paragraph"/><h4>Update</h4><p class="paragraph"/>To update an instance, change some properties and then call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> again:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
p.name = <span class="java&#45;quote">"Bob"</span>
p.save()</pre></div><p class="paragraph"/><h4>Delete</h4><p class="paragraph"/>To delete an instance use the <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> method:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
p.delete()</pre></div>


<a name="5.2 Domain Modelling in GORM"><!-- Legacy link --></a>
<h2 id="domainClasses">6.2 Domain Modelling in GORM</h2>
When building Grails applications you have to consider the problem domain you are trying to solve. For example if you were building an <a href="http://www.amazon.com/" target="blank">Amazon</a>-style bookstore you would be thinking about books, authors, customers and publishers to name a few.<p class="paragraph"/>These are modeled in GORM as Groovy classes, so a <code>Book</code> class may have a title, a release date, an ISBN number and so on. The next few sections show how to model the domain in GORM.<p class="paragraph"/>To create a domain class you run the <a href="../ref/Command Line/create-domain-class.html" class="commandLine">create-domain-class</a> command as follows:<p class="paragraph"/><div class="code"><pre>grails create&#45;domain&#45;class org.bookstore.Book</pre></div><p class="paragraph"/>The result will be a class at <code>grails-app/domain/org/bookstore/Book.groovy</code>:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">package</span> org.bookstore<p class="paragraph"/>class Book &#123;
&#125;</pre></div><p class="paragraph"/>This class will map automatically to a table in the database called <code>book</code> (the same name as the class). This behaviour is customizable through the <a href="../guide/single.html#ormdsl" class="guide">ORM Domain Specific Language</a><p class="paragraph"/>Now that you have a domain class you can define its properties as Java types. For example:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">package</span> org.bookstore<p class="paragraph"/>class Book &#123;
    <span class="java&#45;object">String</span> title
    Date releaseDate
    <span class="java&#45;object">String</span> ISBN
&#125;</pre></div><p class="paragraph"/>Each property is mapped to a column in the database, where the convention for column names is all lower case separated by underscores. For example <code>releaseDate</code> maps onto a column <code>release_date</code>. The SQL types are auto-detected from the Java types, but can be customized with <a href="../guide/single.html#constraints" class="guide">Constraints</a> or the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a>.


<a name="5.2.1 Association in GORM"><!-- Legacy link --></a>
<h2 id="gormAssociation">6.2.1 Association in GORM</h2>
Relationships define how domain classes interact with each other. Unless specified explicitly at both ends, a relationship exists only in the direction it is defined.<p class="paragraph"/>

<a name="5.2.1.1 Many-to-one and one-to-one"><!-- Legacy link --></a>
<h2 id="manyToOneAndOneToOne">6.2.1.1 Many-to-one and one-to-one</h2>
A many-to-one relationship is the simplest kind, and is defined with a property of the type of another domain class. Consider this example:<p class="paragraph"/><h5>Example A</h5><p class="paragraph"/><div class="code"><pre>class Face &#123;
    Nose nose
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
&#125;</pre></div><p class="paragraph"/>In this case we have a unidirectional many-to-one relationship from <code>Face</code> to <code>Nose</code>. To make this relationship bidirectional define the other side as follows:<p class="paragraph"/><h5>Example B</h5><p class="paragraph"/><div class="code"><pre>class Face &#123;
    Nose nose
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
    <span class="java&#45;keyword">static</span> belongsTo = &#91;face:Face&#93;
&#125;</pre></div><p class="paragraph"/>In this case we use the <code>belongsTo</code> setting to say that <code>Nose</code> "belongs to" <code>Face</code>. The result of this is that we can create a <code>Face</code>, attach a <code>Nose</code> instance to it and when we save or delete the <code>Face</code> instance, GORM will save or delete the <code>Nose</code>. In other words, saves and deletes will cascade from <code>Face</code> to the associated <code>Nose</code>:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">new</span> Face(nose:<span class="java&#45;keyword">new</span> Nose()).save()</pre></div><p class="paragraph"/>The example above will save both face and nose. Note that the inverse  <em class="italic">is not</em>  true and will result in an error due to a transient <code>Face</code>:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">new</span> Nose(face:<span class="java&#45;keyword">new</span> Face()).save() // will cause an error</pre></div><p class="paragraph"/>Now if we delete the <code>Face</code> instance, the <code>Nose</code> will go too:<p class="paragraph"/><div class="code"><pre>def f = Face.get(1)
f.delete() // both Face and Nose deleted</pre></div><p class="paragraph"/>To make the relationship a true one-to-one, use the <code>hasOne</code> property on the owning side, e.g. <code>Face</code>:<p class="paragraph"/><h5>Example C</h5><p class="paragraph"/><div class="code"><pre>class Face &#123;
    <span class="java&#45;keyword">static</span> hasOne = &#91;nose:Nose&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
    Face face
&#125;</pre></div><p class="paragraph"/>Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the foreign key column is stored in the <code>nose</code> table inside a column called <code>face_id</code>. Also, <code>hasOne</code> only works with bidirectional relationships.<p class="paragraph"/>Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:<p class="paragraph"/><div class="code"><pre>class Face &#123;
    <span class="java&#45;keyword">static</span> hasOne = &#91;nose:Nose&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> constraints = &#123;
        nose unique: <span class="java&#45;keyword">true</span>
    &#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Nose &#123;
    Face face
&#125;</pre></div>


<a name="5.2.1.2 One-to-many"><!-- Legacy link --></a>
<h2 id="oneToMany">6.2.1.2 One-to-many</h2>
A one-to-many relationship is when one class, example <code>Author</code>, has many instances of another class, example <code>Book</code>. With Grails you define such a relationship with the <code>hasMany</code> setting:<p class="paragraph"/><div class="code"><pre>class Author &#123;
    <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;<p class="paragraph"/>    <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Book &#123;
    <span class="java&#45;object">String</span> title
&#125;</pre></div><p class="paragraph"/>In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.<p class="paragraph"/><blockquote class="note">
The <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a> allows mapping unidirectional relationships using a foreign key association instead
</blockquote><p class="paragraph"/>Grails will automatically inject a property of type <code>java.util.Set</code> into the domain class based on the <code>hasMany</code> setting. This can be used to iterate over the collection:<p class="paragraph"/><div class="code"><pre>def a = Author.get(1)<p class="paragraph"/><span class="java&#45;keyword">for</span> (book in a.books) &#123;
    println book.title
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
The default fetch strategy used by Grails is "lazy", which means that the collection will be lazily initialized on first access. This can lead to the <a href="http://www.javalobby.org/java/forums/t20533.html" target="blank">n+1 problem</a> if you are not careful.<p class="paragraph"/>If you need "eager" fetching you can use the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a> or specify eager fetching as part of a <a href="../guide/single.html#querying" class="guide">query</a>
</blockquote><p class="paragraph"/>The default cascading behaviour is to cascade saves and updates, but not deletes unless a <code>belongsTo</code> is also specified:<p class="paragraph"/><div class="code"><pre>class Author &#123;
    <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;<p class="paragraph"/>    <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Book &#123;
    <span class="java&#45;keyword">static</span> belongsTo = &#91;author: Author&#93;
    <span class="java&#45;object">String</span> title
&#125;</pre></div><p class="paragraph"/>If you have two properties of the same type on the many side of a one-to-many you have to use <code>mappedBy</code> to specify which the collection is mapped:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    <span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
    <span class="java&#45;keyword">static</span> mappedBy = &#91;flights: <span class="java&#45;quote">"departureAirport"</span>&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
    Airport departureAirport
    Airport destinationAirport
&#125;</pre></div><p class="paragraph"/>This is also true if you have multiple collections that map to different properties on the many side:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    <span class="java&#45;keyword">static</span> hasMany = &#91;outboundFlights: Flight, inboundFlights: Flight&#93;
    <span class="java&#45;keyword">static</span> mappedBy = &#91;outboundFlights: <span class="java&#45;quote">"departureAirport"</span>,
                       inboundFlights: <span class="java&#45;quote">"destinationAirport"</span>&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
    Airport departureAirport
    Airport destinationAirport
&#125;</pre></div><p class="paragraph"/>

<a name="5.2.1.3 Many-to-many"><!-- Legacy link --></a>
<h2 id="manyToMany">6.2.1.3 Many-to-many</h2>
Grails supports many-to-many relationships by defining a <code>hasMany</code> on both sides of the relationship and having a <code>belongsTo</code> on the owned side of the relationship:<p class="paragraph"/><div class="code"><pre>class Book &#123;
    <span class="java&#45;keyword">static</span> belongsTo = Author
    <span class="java&#45;keyword">static</span> hasMany = &#91;authors:Author&#93;
    <span class="java&#45;object">String</span> title
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Author &#123;
    <span class="java&#45;keyword">static</span> hasMany = &#91;books:Book&#93;
    <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/>Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case <code>Author</code>, takes responsibility for persisting the relationship and is the only side that can cascade saves across.<p class="paragraph"/>For example this will work and cascade saves:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">new</span> Author(name:<span class="java&#45;quote">"Stephen King"</span>)
        .addToBooks(<span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"The Stand"</span>))
        .addToBooks(<span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"The Shining"</span>))
        .save()</pre></div><p class="paragraph"/>However this will only save the <code>Book</code> and not the authors!<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">new</span> Book(name:<span class="java&#45;quote">"Groovy in Action"</span>)
        .addToAuthors(<span class="java&#45;keyword">new</span> Author(name:<span class="java&#45;quote">"Dierk Koenig"</span>))
        .addToAuthors(<span class="java&#45;keyword">new</span> Author(name:<span class="java&#45;quote">"Guillaume Laforge"</span>))
        .save()</pre></div><p class="paragraph"/>This is the expected behaviour as, just like Hibernate, only one side of a many-to-many can take responsibility for managing the relationship.<p class="paragraph"/><blockquote class="warning">
Grails' <a href="../guide/single.html#scaffolding" class="guide">Scaffolding</a> feature <strong class="bold">does not</strong> currently support many-to-many relationship and hence you must write the code to manage the relationship yourself
</blockquote>


<a name="5.2.1.4 Basic Collection Types"><!-- Legacy link --></a>
<h2 id="basicCollectionTypes">6.2.1.4 Basic Collection Types</h2>
As well as associations between different domain classes, GORM also supports mapping of basic collection types.
For example, the following class creates a <code>nicknames</code> association that is a <code>Set</code> of <code>String</code> instances:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    <span class="java&#45;keyword">static</span> hasMany = &#91;nicknames: <span class="java&#45;object">String</span>&#93;
&#125;</pre></div><p class="paragraph"/>GORM will map an association like the above using a join table. You can alter various aspects of how the join table is mapped using the <code>joinTable</code> argument:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;nicknames: <span class="java&#45;object">String</span>&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
       hasMany joinTable: &#91;name: 'bunch_o_nicknames',
                           key: 'person_id',
                           column: 'nickname',
                           type: <span class="java&#45;quote">"text"</span>&#93;
    &#125;
&#125;</pre></div><p class="paragraph"/>The example above will map to a table that looks like the following:<p class="paragraph"/><strong class="bold">bunch_o_nicknames Table</strong>
<div class="code"><pre>&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;
| person_id         |     nickname          |
&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;
|   1               |      Fred             |
&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;</pre></div>

<a name="5.2.2 Composition in GORM"><!-- Legacy link --></a>
<h2 id="gormComposition">6.2.2 Composition in GORM</h2>
As well as <a href="../guide/single.html#gormAssociation" class="guide">association</a>, Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a class can be "embedded" within the current table. For example:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    Address homeAddress
    Address workAddress
    <span class="java&#45;keyword">static</span> embedded = &#91;'homeAddress', 'workAddress'&#93;
&#125;<p class="paragraph"/>class Address &#123;
    <span class="java&#45;object">String</span> number
    <span class="java&#45;object">String</span> code
&#125;</pre></div><p class="paragraph"/>The resulting mapping would looking like this:<p class="paragraph"/><img border="0" class="center" src="../img/5.2.2-composition.jpg"></img><p class="paragraph"/><blockquote class="note">
If you define the <code>Address</code> class in a separate Groovy file in the <code>grails-app/domain</code> directory you will also get an <code>address</code> table. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the <code>Address</code> class below the <code>Person</code> class in the <code>grails-app/domain/Person.groovy</code> file
</blockquote>


<a name="5.2.3 Inheritance in GORM"><!-- Legacy link --></a>
<h2 id="inheritanceInGORM">6.2.3 Inheritance in GORM</h2>
GORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:<p class="paragraph"/><div class="code"><pre>class Content &#123;
     <span class="java&#45;object">String</span> author
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class BlogEntry <span class="java&#45;keyword">extends</span> Content &#123;
    URL url
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">extends</span> Content &#123;
    <span class="java&#45;object">String</span> ISBN
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class PodCast <span class="java&#45;keyword">extends</span> Content &#123;
    <span class="java&#45;object">byte</span>&#91;&#93; audioStream
&#125;</pre></div><p class="paragraph"/>In the above example we have a parent <code>Content</code> class and then various child classes with more specific behaviour.<p class="paragraph"/><h4>Considerations</h4><p class="paragraph"/>At the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called <code>class</code> so the parent class (<code>Content</code>) and its subclasses (<code>BlogEntry</code>, <code>Book</code> etc.), share the <strong class="bold">same</strong> table.<p class="paragraph"/>Table-per-hierarchy mapping has a down side in that you <strong class="bold">cannot</strong> have non-nullable properties with inheritance mapping. An alternative is to use table-per-subclass which can be enabled with the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a><p class="paragraph"/>However, excessive use of inheritance and table-per-subclass can result in poor query performance due to the use of outer join queries. In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy too deep.<p class="paragraph"/><h4>Polymorphic Queries</h4><p class="paragraph"/>The upshot of inheritance is that you get the ability to polymorphically query. For example using the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method on the <code>Content</code> super class will return all subclasses of <code>Content</code>:<p class="paragraph"/><div class="code"><pre>def content = Content.list() // list all blog entries, books and podcasts
content = Content.findAllByAuthor('Joe Bloggs') // find all by author<p class="paragraph"/>def podCasts = PodCast.list() // list only podcasts</pre></div>

<a name="5.2.4 Sets, Lists and Maps"><!-- Legacy link --></a>
<h2 id="sets,ListsAndMaps">6.2.4 Sets, Lists and Maps</h2>
<h4>Sets of Objects</h4><p class="paragraph"/>By default when you define a relationship with GORM it is a <code>java.util.Set</code> which is an unordered collection that cannot contain duplicates. In other words when you have:<p class="paragraph"/><div class="code"><pre>class Author &#123;
    <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</pre></div><p class="paragraph"/>The books property that GORM injects is a <code>java.util.Set</code>. Sets guarantee uniquenes but not order, which may not be what you want. To have custom ordering you configure the Set as a <code>SortedSet</code>:<p class="paragraph"/><div class="code"><pre>class Author &#123;<p class="paragraph"/>    SortedSet books<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</pre></div><p class="paragraph"/>In this case a <code>java.util.SortedSet</code> implementation is used which means you must implement <code>java.lang.Comparable</code> in your Book class:<p class="paragraph"/><div class="code"><pre>class Book <span class="java&#45;keyword">implements</span> Comparable &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> title
    Date releaseDate = <span class="java&#45;keyword">new</span> Date()<p class="paragraph"/>    <span class="java&#45;object">int</span> compareTo(obj) &#123;
        releaseDate.compareTo(obj.releaseDate)
    &#125;
&#125;</pre></div><p class="paragraph"/>The result of the above class is that the Book instances in the books collection of the Author class will be ordered by their release date.<p class="paragraph"/><h4>Lists of Objects</h4><p class="paragraph"/>To keep objects in the order which they were added and to be able to reference them by index like an array you can define your collection type as a <code>List</code>:<p class="paragraph"/><div class="code"><pre>class Author &#123;<p class="paragraph"/>    List books<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</pre></div><p class="paragraph"/>In this case when you add new elements to the books collection the order is retained in a sequential list indexed from 0 so you can do:<p class="paragraph"/><div class="code"><pre>author.books&#91;0&#93; // get the first book</pre></div><p class="paragraph"/>The way this works at the database level is Hibernate creates a <code>books_idx</code> column where it saves the index of the elements in the collection to retain this order at the database level.<p class="paragraph"/>When using a <code>List</code>, elements must be added to the collection before being saved, otherwise Hibernate will throw an exception (<code>org.hibernate.HibernateException</code>: null index column for collection):<p class="paragraph"/><div class="code"><pre>// This won't work!
def book = <span class="java&#45;keyword">new</span> Book(title: 'The Shining')
book.save()
author.addToBooks(book)<p class="paragraph"/>// Do it <span class="java&#45;keyword">this</span> way instead.
def book = <span class="java&#45;keyword">new</span> Book(title: 'Misery')
author.addToBooks(book)
author.save()</pre></div><p class="paragraph"/><h4>Bags of Objects</h4><p class="paragraph"/>If ordering and uniqueness aren't a concern (or if you manage these explicitly) then you can use the Hibernate <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html" target="blank">Bag</a> type to represent mapped collections.<p class="paragraph"/>The only change required for this is to define the collection type as a <code>Collection</code>:<p class="paragraph"/><div class="code"><pre>class Author &#123;<p class="paragraph"/>   Collection books<p class="paragraph"/>   <span class="java&#45;keyword">static</span> hasMany = &#91;books: Book&#93;
&#125;</pre></div><p class="paragraph"/>Since uniqueness and order aren't managed by Hibernate, adding to or removing from collections mapped as a Bag don't trigger a load of all existing instances from the database, so this approach will perform better and require less memory than using a <code>Set</code> or a <code>List</code>.<p class="paragraph"/><h4>Maps of Objects</h4><p class="paragraph"/>If you want a simple map of string/value pairs GORM can map this with the following:<p class="paragraph"/><div class="code"><pre>class Author &#123;
    Map books // map of ISBN:book names
&#125;<p class="paragraph"/>def a = <span class="java&#45;keyword">new</span> Author()
a.books = &#91;<span class="java&#45;quote">"1590597583"</span>:<span class="java&#45;quote">"Grails Book"</span>&#93;
a.save()</pre></div>
In this case the key and value of the map MUST be strings.<p class="paragraph"/>If you want a Map of objects then you can do this:<p class="paragraph"/><div class="code"><pre>class Book &#123;<p class="paragraph"/>    Map authors<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;authors: Author&#93;
&#125;<p class="paragraph"/>def a = <span class="java&#45;keyword">new</span> Author(name:<span class="java&#45;quote">"Stephen King"</span>)<p class="paragraph"/>def book = <span class="java&#45;keyword">new</span> Book()
book.authors = &#91;stephen:a&#93;
book.save()</pre></div><p class="paragraph"/>The static <code>hasMany</code> property defines the type of the elements within the Map. The keys for the map <strong class="bold">must</strong> be strings.<p class="paragraph"/><h4>A Note on Collection Types and Performance</h4><p class="paragraph"/>The Java <code>Set</code> type doesn't allow duplicates. To ensure uniqueness when adding an entry to a <code>Set</code> association Hibernate has to load the entire associations from the database. If you have a large numbers of entries in the association this can be costly in terms of performance.<p class="paragraph"/>The same behavior is required for <code>List</code> types, since Hibernate needs to load the entire association to maintain order. Therefore it is recommended that if you anticipate a large numbers of records in the association that you make the association bidirectional so that the link can be created on the inverse side. For example consider the following code:<p class="paragraph"/><div class="code"><pre>def book = <span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"New Grails Book"</span>)
def author = Author.get(1)
book.author = author
book.save()</pre></div><p class="paragraph"/>In this example the association link is being created by the child (Book) and hence it is not necessary to manipulate the collection directly resulting in fewer queries and more efficient code. Given an <code>Author</code> with a large number of associated <code>Book</code> instances if you were to write code like the following you would see an impact on performance:<p class="paragraph"/><div class="code"><pre>def book = <span class="java&#45;keyword">new</span> Book(title:<span class="java&#45;quote">"New Grails Book"</span>)
def author = Author.get(1)
author.addToBooks(book)
author.save()</pre></div><p class="paragraph"/>You could also model the collection as a Hibernate Bag as described above.


<a name="5.3 Persistence Basics"><!-- Legacy link --></a>
<h2 id="persistenceBasics">6.3 Persistence Basics</h2>
A key thing to remember about Grails is that under the surface Grails is using <a href="http://www.hibernate.org/" target="blank">Hibernate</a> for persistence. If you are coming from a background of using <a href="http://wiki.rubyonrails.org/rails/pages/ActiveRecord" target="blank">ActiveRecord</a> or <a href="http://www.mybatis.org/" target="blank">iBatis/MyBatis</a>, Hibernate's "session" model may feel a little strange.<p class="paragraph"/>Grails automatically binds a Hibernate session to the currently executing request. This lets you use the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> and <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> methods as well as other GORM methods transparently.<p class="paragraph"/><h4>Transactional Write-Behind</h4><p class="paragraph"/>A useful feature of Hibernate over direct JDBC calls and even other frameworks is that when you call <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> or <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> it does not necessarily perform any SQL operations <strong class="bold">at that point</strong>. Hibernate batches up SQL statements and executes them as late as possible, often at the end of the request when flushing and closing the session. This is typically done for you automatically by Grails, which manages your Hibernate session.<p class="paragraph"/>Hibernate caches database updates where possible, only actually pushing the changes when it knows that a flush is required, or when a flush is triggered programmatically. One common case where Hibernate will flush cached updates is when performing queries since the cached information might be included in the query results. But as long as you're doing non-conflicting saves, updates, and deletes, they'll be batched until the session is flushed. This can be a significant performance boost for applications that do a lot of database writes.<p class="paragraph"/>Note that flushing is not the same as committing a transaction. If your actions are performed in the context of a transaction, flushing will execute SQL updates but the database will save the changes in its transaction queue and only finalize the updates when the transaction commits.


<a name="5.3.1 Saving and Updating"><!-- Legacy link --></a>
<h2 id="savingAndUpdating">6.3.1 Saving and Updating</h2>
An example of using the <a href="../ref/Domain Classes/save.html" class="domainClasses">save</a> method can be seen below:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
p.save()</pre></div><p class="paragraph"/>This save will be not be pushed to the database immediately - it will be pushed when the next flush occurs. But there are occasions when you want to control when those statements are executed or, in Hibernate terminology, when the session is "flushed". To do so you can use the flush argument to the save method:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
p.save(flush: <span class="java&#45;keyword">true</span>)</pre></div><p class="paragraph"/>Note that in this case  <em class="italic">all</em>  pending SQL statements including previous saves, deletes, etc. will be synchronized with the database. This also lets you catch any exceptions, which is typically useful in highly concurrent scenarios involving <a href="../guide/single.html#locking" class="guide">optimistic locking</a>:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
<span class="java&#45;keyword">try</span> &#123;
    p.save(flush: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (org.springframework.dao.DataIntegrityViolationException e) &#123;
    // deal with exception
&#125;</pre></div><p class="paragraph"/>Another thing to bear in mind is that Grails <a href="../guide/single.html#validation" class="guide">validates</a> a domain instance every time you save it. If that validation fails the domain instance will  <em class="italic">not</em>  be persisted to the database. By default, <code>save()</code> will simply return <code>null</code> in this case, but if you would prefer it to throw an exception you can use the <code>failOnError</code> argument:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
<span class="java&#45;keyword">try</span> &#123;
    p.save(failOnError: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (ValidationException e) &#123;
    // deal with exception
&#125;</pre></div><p class="paragraph"/>You can even change the default behaviour with a setting in <code>Config.groovy</code>, as described in the <a href="../guide/single.html#configGORM" class="guide">section on configuration</a>. Just remember that when you are saving domain instances that have been bound with data provided by the user, the likelihood of validation exceptions is quite high and you won't want those exceptions propagating to the end user.<p class="paragraph"/>You can find out more about the subtleties of saving data in <a href="http://blog.springsource.com/2010/06/23/gorm-gotchas-part-1/" target="blank">this article</a> - a must read!


<a name="5.3.2 Deleting Objects"><!-- Legacy link --></a>
<h2 id="deletingObjects">6.3.2 Deleting Objects</h2>
An example of the <a href="../ref/Domain Classes/delete.html" class="domainClasses">delete</a> method can be seen below:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
p.delete()</pre></div><p class="paragraph"/>As with saves, Hibernate will use transactional write-behind to perform the delete; to perform the delete in-place you can use the <code>flush</code> argument:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)
p.delete(flush: <span class="java&#45;keyword">true</span>)</pre></div><p class="paragraph"/>Using the <code>flush</code> argument lets you catch any errors that occur during a delete. A common error that may occur is if you violate a database constraint, although this is normally down to a programming or schema error. The following example shows how to catch a <code>DataIntegrityViolationException</code> that is thrown when you violate the database constraints:<p class="paragraph"/><div class="code"><pre>def p = Person.get(1)<p class="paragraph"/><span class="java&#45;keyword">try</span> &#123;
    p.delete(flush: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (org.springframework.dao.DataIntegrityViolationException e) &#123;
    flash.message = <span class="java&#45;quote">"Could not delete person $&#123;p.name&#125;"</span>
    redirect(action: <span class="java&#45;quote">"show"</span>, id: p.id)
&#125;</pre></div><p class="paragraph"/>Note that Grails does not supply a <code>deleteAll</code> method as deleting data is discouraged and can often be avoided through boolean flags/logic.<p class="paragraph"/>If you really need to batch delete data you can use the <a href="../ref/Domain Classes/executeUpdate.html" class="domainClasses">executeUpdate</a> method to do batch DML statements:<p class="paragraph"/><div class="code"><pre>Customer.executeUpdate(<span class="java&#45;quote">"delete Customer c where c.name = :oldName"</span>,
                       &#91;oldName: <span class="java&#45;quote">"Fred"</span>&#93;)</pre></div><p class="paragraph"/>

<a name="5.3.3 Understanding Cascading Updates and Deletes"><!-- Legacy link --></a>
<h2 id="cascades">6.3.3 Understanding Cascading Updates and Deletes</h2>
It is critical that you understand how cascading updates and deletes work when using GORM. The key part to remember is the <code>belongsTo</code> setting which controls which class "owns" a relationship.<p class="paragraph"/>Whether it is a one-to-one, one-to-many or many-to-many, defining <code>belongsTo</code> will result in updates cascading from the owning class to its dependant (the other side of the relationship), and for many-/one-to-one and one-to-many relationships deletes will also cascade.<p class="paragraph"/>If you  <em class="italic">do not</em>  define <code>belongsTo</code> then no cascades will happen and you will have to manually save each object (except in the case of the one-to-many, in which case saves will cascade automatically if a new instance is in a <code>hasMany</code> collection).<p class="paragraph"/>Here is an example:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    <span class="java&#45;object">String</span> name
    <span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
    <span class="java&#45;object">String</span> number
    <span class="java&#45;keyword">static</span> belongsTo = &#91;airport: Airport&#93;
&#125;</pre></div><p class="paragraph"/>If I now create an <code>Airport</code> and add some <code>Flight</code>s to it I can save the <code>Airport</code> and have the updates cascaded down to each flight, hence saving the whole object graph:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">new</span> Airport(name: <span class="java&#45;quote">"Gatwick"</span>)
        .addToFlights(<span class="java&#45;keyword">new</span> Flight(number: <span class="java&#45;quote">"BA3430"</span>))
        .addToFlights(<span class="java&#45;keyword">new</span> Flight(number: <span class="java&#45;quote">"EZ0938"</span>))
        .save()</pre></div><p class="paragraph"/>Conversely if I later delete the <code>Airport</code> all <code>Flight</code>s associated with it will also be deleted:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java&#45;quote">"Gatwick"</span>)
airport.delete()</pre></div><p class="paragraph"/>However, if I were to remove <code>belongsTo</code> then the above cascading deletion code <strong class="bold">would not work</strong>. To understand this better take a look at the summaries below that describe the default behaviour of GORM with regards to specific associations. Also read <a href="http://blog.springsource.com/2010/07/02/gorm-gotchas-part-2/" target="blank">part 2</a> of the GORM Gotchas series of articles to get a deeper understanding of relationships and cascading.<p class="paragraph"/><h5>Bidirectional one-to-many with belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A &#123; <span class="java&#45;keyword">static</span> hasMany = &#91;bees: B&#93; &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123; <span class="java&#45;keyword">static</span> belongsTo = &#91;a: A&#93; &#125;</pre></div><p class="paragraph"/>In the case of a bidirectional one-to-many where the many side defines a <code>belongsTo</code> then the cascade strategy is set to "ALL" for the one side and "NONE" for the many side.<p class="paragraph"/><h5>Unidirectional one-to-many</h5><p class="paragraph"/><div class="code"><pre>class A &#123; <span class="java&#45;keyword">static</span> hasMany = &#91;bees: B&#93; &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123;  &#125;</pre></div><p class="paragraph"/>In the case of a unidirectional one-to-many where the many side defines no belongsTo then the cascade strategy is set to "SAVE-UPDATE".<p class="paragraph"/><h5>Bidirectional one-to-many, no belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A &#123; <span class="java&#45;keyword">static</span> hasMany = &#91;bees: B&#93; &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123; A a &#125;</pre></div><p class="paragraph"/>In the case of a bidirectional one-to-many where the many side does not define a <code>belongsTo</code> then the cascade strategy is set to "SAVE-UPDATE" for the one side and "NONE" for the many side.<p class="paragraph"/><h5>Unidirectional one-to-one with belongsTo</h5><p class="paragraph"/><div class="code"><pre>class A &#123;  &#125;</pre></div><p class="paragraph"/><div class="code"><pre>class B &#123; <span class="java&#45;keyword">static</span> belongsTo = &#91;a: A&#93; &#125;</pre></div><p class="paragraph"/>In the case of a unidirectional one-to-one association that defines a <code>belongsTo</code> then the cascade strategy is set to "ALL" for the owning side of the relationship (A-&#62;B) and "NONE" from the side that defines the <code>belongsTo</code> (B-&#62;A)<p class="paragraph"/>Note that if you need further control over cascading behaviour, you can use the <a href="../guide/single.html#ormdsl" class="guide">ORM DSL</a>.


<a name="5.3.4 Eager and Lazy Fetching"><!-- Legacy link --></a>
<h2 id="fetching">6.3.4 Eager and Lazy Fetching</h2>
Associations in GORM are by default lazy. This is best explained by example:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    <span class="java&#45;object">String</span> name
    <span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Flight &#123;
    <span class="java&#45;object">String</span> number
    Location destination
    <span class="java&#45;keyword">static</span> belongsTo = &#91;airport: Airport&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Location &#123;
    <span class="java&#45;object">String</span> city
    <span class="java&#45;object">String</span> country
&#125;</pre></div><p class="paragraph"/>Given the above domain classes and the following code:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java&#45;quote">"Gatwick"</span>)
<span class="java&#45;keyword">for</span> (flight in airport.flights) &#123;
    println flight.destination.city
&#125;</pre></div><p class="paragraph"/>GORM will execute a single SQL query to fetch the <code>Airport</code> instance, another to get its flights, and then 1 extra query for  <em class="italic">each iteration</em>  over the <code>flights</code> association to get the current flight's destination. In other words you get N+1 queries (if you exclude the original one to get the airport).<p class="paragraph"/><h3>Configuring Eager Fetching</h3><p class="paragraph"/>An alternative approach that avoids the N+1 queries is to use eager fetching, which can be specified as follows:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    <span class="java&#45;object">String</span> name
    <span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        flights lazy: <span class="java&#45;keyword">false</span>
    &#125;
&#125;</pre></div><p class="paragraph"/>In this case the <code>flights</code> association will be loaded at the same time as its <code>Airport</code> instance, although a second query will be executed to fetch the collection. You can also use <code>fetch: 'join'</code> instead of <code>lazy: false</code> , in which case GORM will only execute a single query to get the airports and their flights. This works well for single-ended associations, but you need to be careful with one-to-manys. Queries will work as you'd expect right up to the moment you add a limit to the number of results you want. At that point, you will likely end up with fewer results than you were expecting. The reason for this is quite technical but ultimately the problem arises from GORM using a left outer join.<p class="paragraph"/>So, the recommendation is currently to use <code>fetch: 'join'</code> for single-ended associations and <code>lazy: false</code> for one-to-manys.<p class="paragraph"/>Be careful how and where you use eager loading because you could load your entire database into memory with too many eager associations. You can find more information on the mapping options in the <a href="../guide/single.html#fetchingDSL" class="guide">section on the ORM DSL</a>.<p class="paragraph"/><h3>Using Batch Fetching</h3><p class="paragraph"/>Although eager fetching is appropriate for some cases, it is not always desirable. If you made everything eager you could quite possibly load your entire database into memory resulting in performance and memory problems. An alternative to eager fetching is to use batch fetching. You can configure Hibernate to lazily fetch results in "batches". For example:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    <span class="java&#45;object">String</span> name
    <span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        flights batchSize: 10
    &#125;
&#125;</pre></div><p class="paragraph"/>In this case, due to the <code>batchSize</code> argument, when you iterate over the <code>flights</code> association, Hibernate will fetch results in batches of 10. For example if you had an <code>Airport</code> that had 30 flights, if you didn't configure batch fetching you would get 1 query to fetch the <code>Airport</code> and then <code>30</code> queries to fetch each flight. With batch fetching you get 1 query to fetch the <code>Airport</code> and 3 queries to fetch each <code>Flight</code> in batches of 10. In other words, batch fetching is an optimization of the lazy fetching strategy. Batch fetching can also be configured at the class level as follows:<p class="paragraph"/><div class="code"><pre>class Flight &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        batchSize 10
    &#125;
&#125;</pre></div><p class="paragraph"/>Check out <a href="http://blog.springsource.com/2010/07/28/gorm-gotchas-part-3/" target="blank">part 3</a> of the GORM Gotchas series for more in-depth coverage of this tricky topic.


<a name="5.3.5 Pessimistic and Optimistic Locking"><!-- Legacy link --></a>
<h2 id="locking">6.3.5 Pessimistic and Optimistic Locking</h2>
<h4>Optimistic Locking</h4><p class="paragraph"/>By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate which involves storing a version value in a special <code>version</code> column in the database that is incremented after each update.<p class="paragraph"/>The <code>version</code> column gets read into a <code>version</code> property that contains the current versioned state of persistent instance which you can access:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)<p class="paragraph"/>println airport.version</pre></div><p class="paragraph"/>When you perform updates Hibernate will automatically check the version property against the  version column in the database and if they differ will throw a <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/StaleObjectStateException.html" class="api">StaleObjectException</a>. This will roll back the transaction if one is active.<p class="paragraph"/>This is useful as it allows a certain level of atomicity without resorting to pessimistic locking that has an inherit performance penalty. The downside is that you have to deal with this exception if you have highly concurrent writes. This requires flushing the session:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)<p class="paragraph"/><span class="java&#45;keyword">try</span> &#123;
    airport.name = <span class="java&#45;quote">"Heathrow"</span>
    airport.save(flush: <span class="java&#45;keyword">true</span>)
&#125;
<span class="java&#45;keyword">catch</span> (org.springframework.dao.OptimisticLockingFailureException e) &#123;
    // deal with exception
&#125;</pre></div><p class="paragraph"/>The way you deal with the exception depends on the application. You could attempt a programmatic merge of the data or go back to the user and ask them to resolve the conflict.<p class="paragraph"/>Alternatively, if it becomes a problem you can resort to pessimistic locking.<p class="paragraph"/><blockquote class="note">
The <code>version</code> will only be updated after flushing the session.
</blockquote><p class="paragraph"/><h4>Pessimistic Locking</h4><p class="paragraph"/>Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has the implication that other read operations will be blocking until the lock is released.<p class="paragraph"/>In Grails pessimistic locking is performed on an existing instance with the <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)
airport.lock() // lock <span class="java&#45;keyword">for</span> update
airport.name = <span class="java&#45;quote">"Heathrow"</span>
airport.save()</pre></div><p class="paragraph"/>Grails will automatically deal with releasing the lock for you once the transaction has been committed. However, in the above case what we are doing is "upgrading" from a regular SELECT to a SELECT..FOR UPDATE and another thread could still have updated the record in between the call to <code>get()</code> and the call to <code>lock()</code>.<p class="paragraph"/>To get around this problem you can use the static <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method that takes an id just like <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a>:<p class="paragraph"/><div class="code"><pre>def airport = Airport.lock(10) // lock <span class="java&#45;keyword">for</span> update
airport.name = <span class="java&#45;quote">"Heathrow"</span>
airport.save()</pre></div><p class="paragraph"/>In this case only SELECT..FOR UPDATE is issued.<p class="paragraph"/>As well as the <a href="../ref/Domain Classes/lock.html" class="domainClasses">lock</a> method you can also obtain a pessimistic locking using queries. For example using a dynamic finder:<p class="paragraph"/><div class="code"><pre>def airport = Airport.findByName(<span class="java&#45;quote">"Heathrow"</span>, &#91;lock: <span class="java&#45;keyword">true</span>&#93;)</pre></div><p class="paragraph"/>Or using criteria:<p class="paragraph"/><div class="code"><pre>def airport = Airport.createCriteria().get &#123;
    eq('name', 'Heathrow')
    lock <span class="java&#45;keyword">true</span>
&#125;</pre></div><p class="paragraph"/>

<a name="5.3.6 Modification Checking"><!-- Legacy link --></a>
<h2 id="modificationChecking">6.3.6 Modification Checking</h2>
Once you have loaded and possibly modified a persistent domain class instance, it isn't straightforward to retrieve the original values. If you try to reload the instance using <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> Hibernate will return the current modified instance from its Session cache. Reloading using another query would trigger a flush which could cause problems if your data isn't ready to be flushed yet. So GORM provides some methods to retrieve the original values that Hibernate caches when it loads the instance (which it uses for dirty checking).<p class="paragraph"/><h4>isDirty</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/isDirty.html" class="domainClasses">isDirty</a> method to check if any field has been modified:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)
assert !airport.isDirty()<p class="paragraph"/>airport.properties = params
<span class="java&#45;keyword">if</span> (airport.isDirty()) &#123;
   // <span class="java&#45;keyword">do</span> something based on changed state
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
<code>isDirty()</code> does not currently check collection associations, but it does check all other persistent properties and associations.
</blockquote><p class="paragraph"/>You can also check if individual fields have been modified:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)
assert !airport.isDirty()<p class="paragraph"/>airport.properties = params
<span class="java&#45;keyword">if</span> (airport.isDirty('name')) &#123;
   // <span class="java&#45;keyword">do</span> something based on changed name
&#125;</pre></div><p class="paragraph"/><h4>getDirtyPropertyNames</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/getDirtyPropertyNames.html" class="domainClasses">getDirtyPropertyNames</a> method to retrieve the names of modified fields; this may be empty but will not be null:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)
assert !airport.isDirty()<p class="paragraph"/>airport.properties = params
def modifiedFieldNames = airport.getDirtyPropertyNames()
<span class="java&#45;keyword">for</span> (fieldName in modifiedFieldNames) &#123;
   // <span class="java&#45;keyword">do</span> something based on changed value
&#125;</pre></div><p class="paragraph"/><h4>getPersistentValue</h4><p class="paragraph"/>You can use the <a href="../ref/Domain Classes/getPersistentValue.html" class="domainClasses">getPersistentValue</a> method to retrieve the value of a modified field:<p class="paragraph"/><div class="code"><pre>def airport = Airport.get(10)
assert !airport.isDirty()<p class="paragraph"/>airport.properties = params
def modifiedFieldNames = airport.getDirtyPropertyNames()
<span class="java&#45;keyword">for</span> (fieldName in modifiedFieldNames) &#123;
    def currentValue = airport.<span class="java&#45;quote">"$fieldName"</span>
    def originalValue = airport.getPersistentValue(fieldName)
    <span class="java&#45;keyword">if</span> (currentValue != originalValue) &#123;
        // <span class="java&#45;keyword">do</span> something based on changed value
    &#125;
&#125;</pre></div><p class="paragraph"/>

<a name="5.4 Querying with GORM"><!-- Legacy link --></a>
<h2 id="querying">6.4 Querying with GORM</h2>
GORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query language HQL. Depending on the complexity of the query you have the following options in order of flexibility and power:
<ul class="star">
<li>Dynamic Finders</li>
<li>Where Queries</li>
<li>Criteria Queries</li>
<li>Hibernate Query Language (HQL)</li>
</ul><p class="paragraph"/>In addition, Groovy's ability to manipulate collections with <a href="http://groovy.codehaus.org/GPath" target="blank">GPath</a> and methods like sort, findAll and so on combined with GORM results in a powerful combination.<p class="paragraph"/>However, let's start with the basics.<p class="paragraph"/><h4>Listing instances</h4><p class="paragraph"/>Use the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method to obtain all instances of a given class:<p class="paragraph"/><div class="code"><pre>def books = Book.list()</pre></div><p class="paragraph"/>The <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method supports arguments to perform pagination:<p class="paragraph"/><div class="code"><pre>def books = Book.list(offset:10, max:20)</pre></div><p class="paragraph"/>as well as sorting:<p class="paragraph"/><div class="code"><pre>def books = Book.list(sort:<span class="java&#45;quote">"title"</span>, order:<span class="java&#45;quote">"asc"</span>)</pre></div><p class="paragraph"/>Here, the <code>sort</code> argument is the name of the domain class property that you wish to sort on, and the <code>order</code> argument is either <code>asc</code> for <strong class="bold">asc</strong>ending or <code>desc</code> for <strong class="bold">desc</strong>ending.<p class="paragraph"/><h4>Retrieval by Database  Identifier</h4><p class="paragraph"/>The second basic form of retrieval is by database identifier using the <a href="../ref/Domain Classes/get.html" class="domainClasses">get</a> method:<p class="paragraph"/><div class="code"><pre>def book = Book.get(23)</pre></div><p class="paragraph"/>You can also obtain a list of instances for a set of identifiers using <a href="../ref/Domain Classes/getAll.html" class="domainClasses">getAll</a>:<p class="paragraph"/><div class="code"><pre>def books = Book.getAll(23, 93, 81)</pre></div>


<a name="5.4.1 Dynamic Finders"><!-- Legacy link --></a>
<h2 id="finders">6.4.1 Dynamic Finders</h2>
GORM supports the concept of <strong class="bold">dynamic finders</strong>. A dynamic finder looks like a static method invocation, but the methods themselves don't actually exist in any form at the code level.<p class="paragraph"/>Instead, a method is auto-magically generated using code synthesis at runtime, based on the properties of a given class. Take for example the <code>Book</code> class:<p class="paragraph"/><div class="code"><pre>class Book &#123;
    <span class="java&#45;object">String</span> title
    Date releaseDate
    Author author
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Author &#123;
    <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/>The <code>Book</code> class has properties such as <code>title</code>, <code>releaseDate</code> and <code>author</code>. These can be used by the <a href="../ref/Domain Classes/findBy.html" class="domainClasses">findBy</a> and <a href="../ref/Domain Classes/findAllBy.html" class="domainClasses">findAllBy</a> methods in the form of "method expressions":<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java&#45;quote">"The Stand"</span>)<p class="paragraph"/>book = Book.findByTitleLike(<span class="java&#45;quote">"Harry Pot%"</span>)<p class="paragraph"/>book = Book.findByReleaseDateBetween(firstDate, secondDate)<p class="paragraph"/>book = Book.findByReleaseDateGreaterThan(someDate)<p class="paragraph"/>book = Book.findByTitleLikeOrReleaseDateLessThan(<span class="java&#45;quote">"%Something%"</span>, someDate)</pre></div><p class="paragraph"/><h4>Method Expressions</h4><p class="paragraph"/>A method expression in GORM is made up of the prefix such as <a href="../ref/Domain Classes/findBy.html" class="domainClasses">findBy</a> followed by an expression that combines one or more properties. The basic form is:<p class="paragraph"/><div class="code"><pre>Book.findBy(&#91;Property&#93;&#91;Comparator&#93;&#91;<span class="java&#45;object">Boolean</span> Operator&#93;)?&#91;Property&#93;&#91;Comparator&#93;</pre></div><p class="paragraph"/>The tokens marked with a '?' are optional. Each comparator changes the nature of the query. For example:<p class="paragraph"/><div class="code"><pre>def book = Book.findByTitle(<span class="java&#45;quote">"The Stand"</span>)<p class="paragraph"/>book =  Book.findByTitleLike(<span class="java&#45;quote">"Harry Pot%"</span>)</pre></div><p class="paragraph"/>In the above example the first query is equivalent to equality whilst the latter, due to the <code>Like</code> comparator, is equivalent to a SQL <code>like</code> expression.<p class="paragraph"/>The possible comparators include:
<ul class="star">
<li><code>InList</code> - In the list of given values</li>
<li><code>LessThan</code> - less than a given value</li>
<li><code>LessThanEquals</code> - less than or equal a give value</li>
<li><code>GreaterThan</code> - greater than a given value</li>
<li><code>GreaterThanEquals</code> - greater than or equal a given value</li>
<li><code>Like</code> - Equivalent to a SQL like expression</li>
<li><code>Ilike</code> - Similar to a <code>Like</code>, except case insensitive</li>
<li><code>NotEqual</code> - Negates equality</li>
<li><code>Between</code> - Between two values (requires two arguments)</li>
<li><code>IsNotNull</code> - Not a null value (doesn't take an argument)</li>
<li><code>IsNull</code> - Is a null value (doesn't take an argument)</li>
</ul><p class="paragraph"/>Notice that the last three require different numbers of method arguments compared to the rest, as demonstrated in the following example:<p class="paragraph"/><div class="code"><pre>def now = <span class="java&#45;keyword">new</span> Date()
def lastWeek = now &#45; 7
def book = Book.findByReleaseDateBetween(lastWeek, now)<p class="paragraph"/>books = Book.findAllByReleaseDateIsNull()
books = Book.findAllByReleaseDateIsNotNull()</pre></div><p class="paragraph"/><h4>Boolean logic (AND/OR)</h4><p class="paragraph"/>Method expressions can also use a boolean operator to combine two or more criteria:<p class="paragraph"/><div class="code"><pre>def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan(
                      <span class="java&#45;quote">"%Java%"</span>, <span class="java&#45;keyword">new</span> Date() &#45; 30)</pre></div><p class="paragraph"/>In this case we're using <code>And</code> in the middle of the query to make sure both conditions are satisfied, but you could equally use <code>Or</code>:<p class="paragraph"/><div class="code"><pre>def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan(
                      <span class="java&#45;quote">"%Java%"</span>, <span class="java&#45;keyword">new</span> Date() &#45; 30)</pre></div><p class="paragraph"/>You can combine as many criteria as you like, but they must all be combined with <code>And</code> or all <code>Or</code>. If you need to combine <code>And</code> and <code>Or</code> or if the number of criteria creates a very long method name, just convert the query to a <a href="../guide/single.html#criteria" class="guide">Criteria</a> or <a href="../guide/single.html#hql" class="guide">HQL</a> query.<p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can also be used within queries:<p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java&#45;quote">"Stephen King"</span>)<p class="paragraph"/>def books = author ? Book.findAllByAuthor(author) : &#91;&#93;</pre></div><p class="paragraph"/>In this case if the <code>Author</code> instance is not null we use it in a query to obtain all the <code>Book</code> instances for the given <code>Author</code>.<p class="paragraph"/><h4>Pagination and Sorting</h4><p class="paragraph"/>The same pagination and sorting parameters available on the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method can also be used with dynamic finders by supplying a map as the final parameter:<p class="paragraph"/><div class="code"><pre>def books = Book.findAllByTitleLike(<span class="java&#45;quote">"Harry Pot%"</span>,
               &#91;max: 3, offset: 2, sort: <span class="java&#45;quote">"title"</span>, order: <span class="java&#45;quote">"desc"</span>&#93;)</pre></div>



<h2 id="whereQueries">6.4.2 Where Queries</h2>
The <code>where</code> method, introduced in Grails 2.0, builds on the support for <a href="../guide/single.html#detachedCriteria" class="guide">Detached Criteria</a> by providing an enhanced, compile-time checked query DSL for common queries. The <code>where</code> method is more flexible than dynamic finders, less verbose than criteria and provides a powerful mechanism to compose queries.<p class="paragraph"/><h4>Basic Querying</h4><p class="paragraph"/>The <code>where</code> method accepts a closure that looks very similar to Groovy's regular collection methods. The closure should define the logical criteria in regular Groovy syntax, for example:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
   firstName == <span class="java&#45;quote">"Bart"</span>
&#125;
Person bart = query.find()</pre></div><p class="paragraph"/>The returned object is a <code>DetachedCriteria</code> instance, which means it is not associated with any particular database connection or session. This means you can use the <code>where</code> method to define common queries at the class level:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    <span class="java&#45;keyword">static</span> simpsons = where &#123;
         lastName == <span class="java&#45;quote">"Simpson"</span>
    &#125;
    &#8230;
&#125;
&#8230;
Person.simpsons.each &#123;
    println it.firstname
&#125;</pre></div><p class="paragraph"/>Query execution is lazy and only happens upon usage of the <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance. If you want to execute a where-style query immediately there are variations of the <code>findAll</code> and <code>find</code> methods to accomplish this:<p class="paragraph"/><div class="code"><pre>def results = Person.findAll &#123;
     lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
def results = Person.findAll(sort:<span class="java&#45;quote">"firstName"</span>) &#123;
     lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
Person p = Person.find &#123; firstName == <span class="java&#45;quote">"Bart"</span> &#125;</pre></div><p class="paragraph"/>Each Groovy operator maps onto a regular criteria method. The following table provides a map of Groovy operators to methods:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Operator</th><th>Criteria Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">==</strong></td><td>eq</td><td>Equal to</td></tr><tr class="table-even"><td><strong class="bold">!=</strong></td><td>ne</td><td>Not equal to</td></tr><tr class="table-odd"><td><strong class="bold">&#62;</strong></td><td>gt</td><td>Greater than</td></tr><tr class="table-even"><td><strong class="bold">&#60;</strong></td><td>lt</td><td>Less than</td></tr><tr class="table-odd"><td><strong class="bold">&#62;=</strong></td><td>ge</td><td>Greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold">&#60;=</strong></td><td>le</td><td>Less than or equal to</td></tr><tr class="table-odd"><td><strong class="bold">in</strong></td><td>inList</td><td>Contained within the given list</td></tr><tr class="table-even"><td><strong class="bold">==~</strong></td><td>like</td><td>Like a given string</td></tr><tr class="table-odd"><td><strong class="bold">=~</strong></td><td>ilike</td><td>Case insensitive like</td></tr></table><p class="paragraph"/>It is possible use regular Groovy comparison operators and logic to formulate complex queries:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
    (lastName != <span class="java&#45;quote">"Simpson"</span> &#38;&#38; firstName != <span class="java&#45;quote">"Fred"</span>) || (firstName == <span class="java&#45;quote">"Bart"</span> &#38;&#38; age &#62; 9)
&#125;
def results = query.list(sort:<span class="java&#45;quote">"firstName"</span>)</pre></div><p class="paragraph"/>The Groovy regex matching operators map onto like and ilike queries unless the expression on the right hand side is a <code>Pattern</code> object, in which case they map onto an <code>rlike</code> query:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
     firstName ==~ ~/B.+/
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
Note that <code>rlike</code> queries are only supported if the underlying database supports regular expressions
</blockquote><p class="paragraph"/>A <code>between</code> criteria query can be done by combining the <code>in</code> keyword with a range:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
     age in 18..65
&#125;</pre></div><p class="paragraph"/>Finally, you can do <code>isNull</code> and <code>isNotNull</code> style queries by using <code>null</code> with regular comparison operators:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
     middleName == <span class="java&#45;keyword">null</span>
&#125;</pre></div><p class="paragraph"/><h4>Query Composition</h4><p class="paragraph"/>Since the return value of the <code>where</code> method is a <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance you can compose new queries from the original query:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
     lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
def bartQuery = query.where &#123;
     firstName == <span class="java&#45;quote">"Bart"</span>
&#125;
Person p = bartQuery.find()</pre></div><p class="paragraph"/>Note that you cannot pass a closure defined as a variable into the <code>where</code> method unless it has been explicitly cast to a <code>DetachedCriteria</code> instance. In other words the following will produce an error:<p class="paragraph"/><div class="code"><pre>def callable = &#123;
    lastName == <span class="java&#45;quote">"Simpson"</span>
&#125;
def query = Person.where(callable)</pre></div><p class="paragraph"/>The above must be written as follows:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.gorm.DetachedCriteria<p class="paragraph"/>def callable = &#123;
    lastName == <span class="java&#45;quote">"Simpson"</span>
&#125; as DetachedCriteria&#60;Person&#62;
def query = Person.where(callable)</pre></div><p class="paragraph"/>As you can see the closure definition is cast (using the Groovy <code>as</code> keyword) to a <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance targeted at the <code>Person</code> class.<p class="paragraph"/><h4>Conjunction, Disjunction and Negation</h4><p class="paragraph"/>As mentioned previously you can combine regular Groovy logical operators (<code>||</code> and <code>&#38;&#38;</code>) to form conjunctions and disjunctions:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
    (lastName != <span class="java&#45;quote">"Simpson"</span> &#38;&#38; firstName != <span class="java&#45;quote">"Fred"</span>) || (firstName == <span class="java&#45;quote">"Bart"</span> &#38;&#38; age &#62; 9)
&#125;</pre></div><p class="paragraph"/>You can also negate a logical comparison using <code>!</code>:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
    firstName == <span class="java&#45;quote">"Fred"</span> &#38;&#38; !(lastName == 'Simpson')
&#125;</pre></div><p class="paragraph"/><h4>Property Comparison Queries</h4><p class="paragraph"/>If you use a property name on both the left hand and right side of a comparison expression then the appropriate property comparison criteria is automatically used:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
   firstName == lastName
&#125;</pre></div><p class="paragraph"/>The following table described how each comparison operator maps onto each criteria property comparison method:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Operator</th><th>Criteria Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">==</strong></td><td>eqProperty</td><td>Equal to</td></tr><tr class="table-even"><td><strong class="bold">!=</strong></td><td>neProperty</td><td>Not equal to</td></tr><tr class="table-odd"><td><strong class="bold">&#62;</strong></td><td>gtProperty</td><td>Greater than</td></tr><tr class="table-even"><td><strong class="bold">&#60;</strong></td><td>ltProperty</td><td>Less than</td></tr><tr class="table-odd"><td><strong class="bold">&#62;=</strong></td><td>geProperty</td><td>Greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold">&#60;=</strong></td><td>leProperty</td><td>Less than or equal to</td></tr></table><p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can be queried by using the dot operator to specify the property name of the association to be queried:<p class="paragraph"/><div class="code"><pre>def query = Pet.where &#123;
    owner.firstName == <span class="java&#45;quote">"Joe"</span> || owner.firstName == <span class="java&#45;quote">"Fred"</span>
&#125;</pre></div><p class="paragraph"/>You can group multiple criterion inside a closure method call where the name of the method matches the association name:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
    pets &#123; name == <span class="java&#45;quote">"Jack"</span> || name == <span class="java&#45;quote">"Joe"</span> &#125;
&#125;</pre></div><p class="paragraph"/>This technique can be combined with other top-level criteria:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
     pets &#123; name == <span class="java&#45;quote">"Jack"</span> &#125; || firstName == <span class="java&#45;quote">"Ed"</span>
&#125;</pre></div><p class="paragraph"/>For collection associations it is possible to apply queries to the size of the collection:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
       pets.size() == 2
&#125;</pre></div><p class="paragraph"/>The following table shows which operator maps onto which criteria method for each size() comparison:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Operator</th><th>Criteria Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">==</strong></td><td>sizeEq</td><td>The collection size is equal to</td></tr><tr class="table-even"><td><strong class="bold">!=</strong></td><td>sizeNe</td><td>The collection size is not equal to</td></tr><tr class="table-odd"><td><strong class="bold">&#62;</strong></td><td>sizeGt</td><td>The collection size is greater than</td></tr><tr class="table-even"><td><strong class="bold">&#60;</strong></td><td>sizeLt</td><td>The collection size is less than</td></tr><tr class="table-odd"><td><strong class="bold">&#62;=</strong></td><td>sizeGe</td><td>The collection size is greater than or equal to</td></tr><tr class="table-even"><td><strong class="bold">&#60;=</strong></td><td>sizeLe</td><td>The collection size is less than or equal to</td></tr></table><p class="paragraph"/>
<h4>Subqueries</h4><p class="paragraph"/>It is possible to execute subqueries within where queries. For example to find all the people older than the average age the following query can be used:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">final</span> query = Person.where &#123;
  age &#62; avg(age)
&#125;</pre></div><p class="paragraph"/>The following table lists the possible subqueries:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">avg</strong></td><td>The average of all values</td></tr><tr class="table-even"><td><strong class="bold">sum</strong></td><td>The sum of all values</td></tr><tr class="table-odd"><td><strong class="bold">max</strong></td><td>The maximum value</td></tr><tr class="table-even"><td><strong class="bold">min</strong></td><td>The minimum value</td></tr><tr class="table-odd"><td><strong class="bold">count</strong></td><td>The count of all values</td></tr><tr class="table-even"><td><strong class="bold">property</strong></td><td>Retrieves a property of the resulting entities</td></tr></table><p class="paragraph"/>You can apply additional criteria to any subquery by using the <code>of</code> method and passing in a closure containing the criteria:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
  age &#62; avg(age).of &#123; lastName == <span class="java&#45;quote">"Simpson"</span> &#125; &#38;&#38; firstName == <span class="java&#45;quote">"Homer"</span>
&#125;</pre></div><p class="paragraph"/>Since the <code>property</code> subquery returns multiple results, the criterion used compares all results. For example the following query will find all people younger than people with the surname "Simpson":<p class="paragraph"/><div class="code"><pre>Person.where &#123;
    age &#60; property(age).of &#123; lastName == <span class="java&#45;quote">"Simpson"</span> &#125;
&#125;</pre></div><p class="paragraph"/>
<h4>Other Functions</h4><p class="paragraph"/>There are several functions available to you within the context of a query. These are summarized in the table below:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">second</strong></td><td>The second of a date property</td></tr><tr class="table-even"><td><strong class="bold">minute</strong></td><td>The minute of a date property</td></tr><tr class="table-odd"><td><strong class="bold">hour</strong></td><td>The hour of a date property</td></tr><tr class="table-even"><td><strong class="bold">day</strong></td><td>The day of the month of a date property</td></tr><tr class="table-odd"><td><strong class="bold">month</strong></td><td>The month of a date property</td></tr><tr class="table-even"><td><strong class="bold">year</strong></td><td>The year of a date property</td></tr><tr class="table-odd"><td><strong class="bold">lower</strong></td><td>Converts a string property to upper case</td></tr><tr class="table-even"><td><strong class="bold">upper</strong></td><td>Converts a string property to lower case</td></tr><tr class="table-odd"><td><strong class="bold">length</strong></td><td>The length of a string property</td></tr><tr class="table-even"><td><strong class="bold">trim</strong></td><td>Trims a string property</td></tr></table><p class="paragraph"/><blockquote class="note">
Currently functions can only be applied to properties or associations of domain classes. You cannot, for example, use a function on a result of a subquery. 
</blockquote><p class="paragraph"/>For example the following query can be used to find all pet's born in 2011:<p class="paragraph"/><div class="code"><pre>def query = Pet.where &#123;
    year(birthDate) == 2011
&#125;</pre></div><p class="paragraph"/>You can also apply functions to associations:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
    year(pets.birthDate) == 2009
&#125;</pre></div><p class="paragraph"/>
<h4>Batch Updates and Deletes</h4><p class="paragraph"/>Since each <code>where</code> method call returns a <a href="../guide/single.html#detachedCriteria" class="guide">DetachedCriteria</a> instance, you can use <code>where</code> queries to execute batch operations such as batch updates and deletes. For example, the following query will update all people with the surname "Simpson" to have the surname "Bloggs":<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
    lastName == 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = query.updateAll(lastName:<span class="java&#45;quote">"Bloggs"</span>)</pre></div><p class="paragraph"/><blockquote class="note">
Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed.
</blockquote><p class="paragraph"/>To batch delete records you can use the <code>deleteAll</code> method:<p class="paragraph"/><div class="code"><pre>def query = Person.where &#123;
    lastName == 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = query.deleteAll()</pre></div>

<a name="5.4.2 Criteria"><!-- Legacy link --></a>
<h2 id="criteria">6.4.3 Criteria</h2>
Criteria is an advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better approach than building up query strings using a <code>StringBuffer</code>.<p class="paragraph"/>Criteria can be used either with the <a href="../ref/Domain Classes/createCriteria.html" class="domainClasses">createCriteria</a> or <a href="../ref/Domain Classes/withCriteria.html" class="domainClasses">withCriteria</a> methods. The builder uses Hibernate's Criteria API. The nodes on this builder map the static methods found in the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/criterion/Restrictions.html" class="api">Restrictions</a> class of the Hibernate Criteria API. For example:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria()
def results = c &#123;
    between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
    eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
    or &#123;
        like(<span class="java&#45;quote">"holderFirstName"</span>, <span class="java&#45;quote">"Fred%"</span>)
        like(<span class="java&#45;quote">"holderFirstName"</span>, <span class="java&#45;quote">"Barney%"</span>)
    &#125;
    maxResults(10)
    order(<span class="java&#45;quote">"holderLastName"</span>, <span class="java&#45;quote">"desc"</span>)
&#125;</pre></div><p class="paragraph"/>This criteria will select up to 10 <code>Account</code> objects in a List matching the following criteria:
<ul class="star">
<li><code>balance</code> is between 500 and 1000</li>
<li><code>branch</code> is 'London'</li>
<li><code>holderFirstName</code> starts with 'Fred' or 'Barney'</li>
</ul><p class="paragraph"/>The results will be sorted in descending order by <code>holderLastName</code>.<p class="paragraph"/>If no records are found with the above criteria, an empty List is returned.<p class="paragraph"/><h4>Conjunctions and Disjunctions</h4><p class="paragraph"/>As demonstrated in the previous example you can group criteria in a logical OR using an <code>or { }</code> block:<p class="paragraph"/><div class="code"><pre>or &#123;
    between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
    eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
&#125;</pre></div><p class="paragraph"/>This also works with logical AND:<p class="paragraph"/><div class="code"><pre>and &#123;
    between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
    eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
&#125;</pre></div><p class="paragraph"/>And you can also negate using logical NOT:<p class="paragraph"/><div class="code"><pre>not &#123;
    between(<span class="java&#45;quote">"balance"</span>, 500, 1000)
    eq(<span class="java&#45;quote">"branch"</span>, <span class="java&#45;quote">"London"</span>)
&#125;</pre></div><p class="paragraph"/>All top level conditions are implied to be AND'd together.<p class="paragraph"/><h4>Querying Associations</h4><p class="paragraph"/>Associations can be queried by having a node that matches the property name. For example say the <code>Account</code> class had many <code>Transaction</code> objects:<p class="paragraph"/><div class="code"><pre>class Account &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> hasMany = &#91;transactions: Transaction&#93;
    &#8230;
&#125;</pre></div><p class="paragraph"/>We can query this association by using the property name <code>transaction</code> as a builder node:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria()
def now = <span class="java&#45;keyword">new</span> Date()
def results = c.list &#123;
    transactions &#123;
        between('date', now &#45; 10, now)
    &#125;
&#125;</pre></div><p class="paragraph"/>The above code will find all the <code>Account</code> instances that have performed <code>transactions</code> within the last 10 days.
You can also nest such association queries within logical blocks:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria()
def now = <span class="java&#45;keyword">new</span> Date()
def results = c.list &#123;
    or &#123;
        between('created', now &#45; 10, now)
        transactions &#123;
            between('date', now &#45; 10, now)
        &#125;
    &#125;
&#125;</pre></div><p class="paragraph"/>Here we find all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days.<p class="paragraph"/><h4>Querying with Projections</h4><p class="paragraph"/>Projections may be used to customise the results. Define a "projections" node within the criteria builder tree to use projections. There are equivalent methods within the projections node to the methods found in the Hibernate <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/criterion/Projections.html" class="api">Projections</a> class:<p class="paragraph"/><div class="code"><pre>def c = Account.createCriteria()<p class="paragraph"/>def numberOfBranches = c.get &#123;
    projections &#123;
        countDistinct('branch')
    &#125;
&#125;</pre></div><p class="paragraph"/>When multiple fields are specified in the projection, a List of values will be returned. A single value will be returned otherwise.<p class="paragraph"/><h4>SQL Projections</h4><p class="paragraph"/>The criteria DSL provides access to Hibernate's SQL projection API.<p class="paragraph"/><div class="code"><pre>// Box is a domain class&#8230;
class Box &#123;
    <span class="java&#45;object">int</span> width
    <span class="java&#45;object">int</span> height
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>// Use SQL projections to retrieve the perimeter and area of all of the Box instances&#8230;
def c = Box.createCriteria()<p class="paragraph"/>def results = c.list &#123;
    projections &#123;
      sqlProjection '(2 &#42; (width + height)) as perimiter, (width &#42; height) as area', &#91;'perimeter', 'area'&#93;, &#91;INTEGER, INTEGER&#93;
    &#125;
&#125;</pre></div><p class="paragraph"/>The first argument to the <code>sqlProjection</code> method is the SQL which defines the projections.  The second argument is a list of
Strings which represent column aliases corresponding to the projected values expressed in the SQL.  The third argument
is a list of <code>org.hibernate.type.Type</code> instances which correspond to the projected values expressed in the SQL.  The API
supports all <code>org.hibernate.type.Type</code> objects but constants like INTEGER, LONG, FLOAT etc. are provided by the DSL which
correspond to all of the types defined in <code>org.hibernate.type.StandardBasicTypes</code>.<p class="paragraph"/>Consider that the following table represents the data in the
<code>BOX</code> table.
<table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>width</th><th>height</th></tr><tr class="table-odd"><td>2</td><td>7</td></tr><tr class="table-even"><td>2</td><td>8</td></tr><tr class="table-odd"><td>2</td><td>9</td></tr><tr class="table-even"><td>4</td><td>9</td></tr></table><p class="paragraph"/>The query above would return results like this:<p class="paragraph"/><div class="code"><pre>&#91;&#91;18, 14&#93;, &#91;20, 16&#93;, &#91;22, 18&#93;, &#91;26, 36&#93;&#93;</pre></div><p class="paragraph"/>Each of the inner lists contains the 2 projected values for each <code>Box</code>, perimiter and area.<p class="paragraph"/><blockquote class="note">
Note that if there are other references in scope wherever your criteria query is expressed that have names that conflict 
with any of the type constants described above, the code in your criteria will refer to those references, not the type
constants provided by the DSL.  In the unlikely event of that happening you can disambiguate the conflict by referring
to the fully qualified Hibernate type.  For example <code>StandardBasicTypes.INTEGER</code> instead of <code>INTEGER</code>.
</blockquote><p class="paragraph"/>If only 1 value is being projected, the alias and the type do not need to be included in a list.<p class="paragraph"/><div class="code"><pre>def results = c.list &#123;
    projections &#123;
      sqlProjection 'sum(width &#42; height) as totalArea', 'totalArea', INTEGER
    &#125;
&#125;</pre></div><p class="paragraph"/>That query would return a single result with the value of 84 as the total area of all of the <code>Box</code> instances.<p class="paragraph"/>The DSL supports grouped projections with the <code>sqlGroupProjection</code> method.<p class="paragraph"/><div class="code"><pre>def results = c.list &#123;
    projections &#123;
        sqlGroupProjection 'width, sum(height) as combinedHeightsForThisWidth', 'width', &#91;'width', 'combinedHeightsForThisWidth'&#93;, &#91;INTEGER, INTEGER&#93;
    &#125;
&#125;</pre></div><p class="paragraph"/>The first argument to the <code>sqlProjection</code> method is the SQL which defines the projections.  The second argument represents the
group by clause that should be part of the query.  That string may be single column name or a comma separated list of column
names.  The third argument is a list of
Strings which represent column aliases corresponding to the projected values expressed in the SQL.  The fourth argument
is a list of <code>org.hibernate.type.Type</code> instances which correspond to the projected values expressed in the SQL.<p class="paragraph"/>The query above is projecting the combined heights of boxes grouped by width and would return results that look like this:<p class="paragraph"/><div class="code"><pre>&#91;&#91;2, 24&#93;, &#91;4, 9&#93;&#93;</pre></div><p class="paragraph"/>Each of the inner lists contains 2 values.  The first value is a box width and the second value is the sum of the heights
of all of the boxes which have that width.<p class="paragraph"/><h4>Using SQL Restrictions</h4><p class="paragraph"/>You can access Hibernate's SQL Restrictions capabilities.<p class="paragraph"/><div class="code"><pre>def c = Person.createCriteria()<p class="paragraph"/>def peopleWithShortFirstNames = c.list &#123;
    sqlRestriction <span class="java&#45;quote">"char_length(first_name) &#60;= 4"</span>
&#125;</pre></div><p class="paragraph"/>SQL Restrictions may be parameterized to deal with SQL injection vulnerabilities related to dynamic restrictions.<p class="paragraph"/>
<div class="code"><pre>def c = Person.createCriteria()<p class="paragraph"/>def peopleWithShortFirstNames = c.list &#123;
    sqlRestriction <span class="java&#45;quote">"char_length(first_name) &#60; ? AND char_length(first_name) &#62; ?"</span>, &#91;maxValue, minValue&#93;
&#125;</pre></div><p class="paragraph"/>
<blockquote class="note">
Note that the parameter there is SQL. The <code>first_name</code> attribute referenced in the example refers to the persistence model, not the object model like in HQL queries. The <code>Person</code> property named <code>firstName</code> is mapped to the <code>first_name</code> column in the database and you must refer to that in the <code>sqlRestriction</code> string.<p class="paragraph"/>Also note that the SQL used here is not necessarily portable across databases.
</blockquote><p class="paragraph"/><h4>Using Scrollable Results</h4><p class="paragraph"/>You can use Hibernate's <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/ScrollableResults.html" class="api">ScrollableResults</a> feature by calling the scroll method:<p class="paragraph"/><div class="code"><pre>def results = crit.scroll &#123;
    maxResults(10)
&#125;
def f = results.first()
def l = results.last()
def n = results.next()
def p = results.previous()<p class="paragraph"/>def <span class="java&#45;keyword">future</span> = results.scroll(10)
def accountNumber = results.getLong('number')</pre></div><p class="paragraph"/>To quote the documentation of Hibernate ScrollableResults:<p class="paragraph"/><blockquote class="quote">
A result iterator that allows moving around within the results by arbitrary increments. The Query / ScrollableResults pattern is very similar to the JDBC PreparedStatement/ ResultSet pattern and the semantics of methods of this interface are similar to the similarly named methods on ResultSet.
</blockquote><p class="paragraph"/>Contrary to JDBC, columns of results are numbered from zero.<p class="paragraph"/><h4>Setting properties in the Criteria instance</h4><p class="paragraph"/>If a node within the builder tree doesn't match a particular criterion it will attempt to set a property on the Criteria object itself. This allows full access to all the properties in this class. This example calls <code>setMaxResults</code> and <code>setFirstResult</code> on the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Criteria.html" class="api">Criteria</a> instance:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> org.hibernate.FetchMode as FM
&#8230;
def results = c.list &#123;
    maxResults(10)
    firstResult(50)
    fetchMode(<span class="java&#45;quote">"aRelationship"</span>, FM.JOIN)
&#125;</pre></div><p class="paragraph"/><h4>Querying with Eager Fetching</h4><p class="paragraph"/>In the section on <a href="../guide/single.html#fetching" class="guide">Eager and Lazy Fetching</a> we discussed how to declaratively specify fetching to avoid the N+1 SELECT problem. However, this can also be achieved using a criteria query:<p class="paragraph"/><div class="code"><pre>def criteria = Task.createCriteria()
def tasks = criteria.list&#123;
    eq <span class="java&#45;quote">"assignee.id"</span>, task.assignee.id
    join 'assignee'
    join 'project'
    order 'priority', 'asc'
&#125;</pre></div><p class="paragraph"/>Notice the usage of the <code>join</code> method: it tells the criteria API to use a <code>JOIN</code> to fetch the named associations with the <code>Task</code> instances. It's probably best not to use this for one-to-many associations though, because you will most likely end up with duplicate results. Instead, use the 'select' fetch mode:
<div class="code"><pre><span class="java&#45;keyword">import</span> org.hibernate.FetchMode as FM
&#8230;
def results = Airport.withCriteria &#123;
    eq <span class="java&#45;quote">"region"</span>, <span class="java&#45;quote">"EMEA"</span>
    fetchMode <span class="java&#45;quote">"flights"</span>, FM.SELECT
&#125;</pre></div>
Although this approach triggers a second query to get the <code>flights</code> association, you will get reliable results  - even with the <code>maxResults</code> option.<p class="paragraph"/><blockquote class="note">
<code>fetchMode</code> and <code>join</code> are general settings of the query and can only be specified at the top-level, i.e. you cannot use them inside projections or association constraints.
</blockquote><p class="paragraph"/>An important point to bear in mind is that if you include associations in the query constraints, those associations will automatically be eagerly loaded. For example, in this query:
<div class="code"><pre>def results = Airport.withCriteria &#123;
    eq <span class="java&#45;quote">"region"</span>, <span class="java&#45;quote">"EMEA"</span>
    flights &#123;
        like <span class="java&#45;quote">"number"</span>, <span class="java&#45;quote">"BA%"</span>
    &#125;
&#125;</pre></div>
the <code>flights</code> collection would be loaded eagerly via a join even though the fetch mode has not been explicitly set.<p class="paragraph"/><h4>Method Reference</h4><p class="paragraph"/>If you invoke the builder with no method name such as:<p class="paragraph"/><div class="code"><pre>c &#123; &#8230; &#125;</pre></div><p class="paragraph"/>The build defaults to listing all the results and hence the above is equivalent to:<p class="paragraph"/><div class="code"><pre>c.list &#123; &#8230; &#125;</pre></div><p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">list</strong></td><td>This is the default method. It returns all matching rows.</td></tr><tr class="table-even"><td><strong class="bold">get</strong></td><td>Returns a unique result set, i.e. just one row. The criteria has to be formed that way, that it only queries one row. This method is not to be confused with a limit to just the first row.</td></tr><tr class="table-odd"><td><strong class="bold">scroll</strong></td><td>Returns a scrollable result set.</td></tr><tr class="table-even"><td><strong class="bold">listDistinct</strong></td><td>If subqueries or associations are used, one may end up with the same row multiple times in the result set, this allows listing only distinct entities and is equivalent to <code>DISTINCT_ROOT_ENTITY</code> of the <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/criterion/CriteriaSpecification.html" class="api">CriteriaSpecification</a> class.</td></tr><tr class="table-odd"><td><strong class="bold">count</strong></td><td>Returns the number of matching rows.</td></tr></table>



<h2 id="detachedCriteria">6.4.4 Detached Criteria</h2>
Detached Criteria are criteria queries that are not associated with any given database session/connection. Supported since Grails 2.0, Detached Criteria queries have many uses including allowing you to create common reusable criteria queries, execute subqueries and execute batch updates/deletes.<p class="paragraph"/>
<h4>Building Detached Criteria Queries</h4><p class="paragraph"/>The primary point of entry for using the Detached Criteria is the <code>grails.gorm.DetachedCriteria</code> class which accepts a domain class as the only argument to its constructor:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> grails.gorm.&#42;
&#8230;
def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person)</pre></div><p class="paragraph"/>Once you have obtained a reference to a detached criteria instance you can execute <a href="../guide/single.html#whereQueries" class="guide">where</a> queries or criteria queries to build up the appropriate query. To build a normal criteria query you can use the <code>build</code> method:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
    eq 'lastName', 'Simpson'
&#125;</pre></div><p class="paragraph"/>Note that methods on the <code>DetachedCriteria</code> instance <strong class="bold">do not</strong> mutate the original object but instead return a new query. In other words, you have to use the return value of the <code>build</code> method to obtain the mutated criteria object:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
    eq 'lastName', 'Simpson'
&#125;
def bartQuery = criteria.build &#123;
    eq 'firstName', 'Bart'
&#125;</pre></div><p class="paragraph"/><h4>Executing Detached Criteria Queries</h4><p class="paragraph"/>Unlike regular criteria, Detached Criteria are lazy, in that no query is executed at the point of definition. Once a Detached Criteria query has been constructed then there are a number of useful query methods which are summarized in the table below:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">list</strong></td><td>List all matching entities</td></tr><tr class="table-even"><td><strong class="bold">get</strong></td><td>Return a single matching result</td></tr><tr class="table-odd"><td><strong class="bold">count</strong></td><td>Count all matching records</td></tr><tr class="table-even"><td><strong class="bold">exists</strong></td><td>Return true if any matching records exist</td></tr><tr class="table-odd"><td><strong class="bold">deleteAll</strong></td><td>Delete all matching records</td></tr><tr class="table-even"><td><strong class="bold">updateAll(Map)</strong></td><td>Update all matching records with the given properties</td></tr></table><p class="paragraph"/>As an example the following code will list the first 4 matching records sorted by the <code>firstName</code> property:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
    eq 'lastName', 'Simpson'
&#125;
def results = criteria.list(max:4, sort:<span class="java&#45;quote">"firstName"</span>)</pre></div><p class="paragraph"/>You can also supply additional criteria to the list method:<p class="paragraph"/><div class="code"><pre>def results = criteria.list(max:4, sort:<span class="java&#45;quote">"firstName"</span>) &#123;
    gt 'age', 30
&#125;</pre></div><p class="paragraph"/>To retrieve a single result you can use the <code>get</code> or <code>find</code> methods (which are synonyms):<p class="paragraph"/><div class="code"><pre>Person p = criteria.find() // or criteria.get()</pre></div><p class="paragraph"/>The <code>DetachedCriteria</code> class itself also implements the <code>Iterable</code> interface which means that it can be treated like a list:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
    eq 'lastName', 'Simpson'
&#125;
criteria.each &#123;
    println it.firstName
&#125;</pre></div><p class="paragraph"/>In this case the query is only executed when the <code>each</code> method is called. The same applies to all other Groovy collection iteration methods.<p class="paragraph"/>You can also execute dynamic finders on <code>DetachedCriteria</code> just like on domain classes. For example:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
    eq 'lastName', 'Simpson'
&#125;
def bart = criteria.findByFirstName(<span class="java&#45;quote">"Bart"</span>)</pre></div><p class="paragraph"/><h4>Using Detached Criteria for Subqueries</h4><p class="paragraph"/>Within the context of a regular criteria query you can use <code>DetachedCriteria</code> to execute subquery. For example if you want to find all people who are older than the average age the following query will accomplish that:<p class="paragraph"/><div class="code"><pre>def results = Person.withCriteria &#123;
     gt <span class="java&#45;quote">"age"</span>, <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
         projections &#123;
             avg <span class="java&#45;quote">"age"</span>
         &#125;
     &#125;
     order <span class="java&#45;quote">"firstName"</span>
 &#125;</pre></div><p class="paragraph"/>Notice that in this case the subquery class is the same as the original criteria query class (ie. <code>Person</code>) and hence the query can be shortened to:<p class="paragraph"/><div class="code"><pre>def results = Person.withCriteria &#123;
     gt <span class="java&#45;quote">"age"</span>, &#123;
         projections &#123;
             avg <span class="java&#45;quote">"age"</span>
         &#125;
     &#125;
     order <span class="java&#45;quote">"firstName"</span>
 &#125;</pre></div><p class="paragraph"/>If the subquery class differs from the original criteria query then you will have to use the original syntax.<p class="paragraph"/>In the previous example the projection ensured that only a single result was returned (the average age). If your subquery returns multiple results then there are different criteria methods that need to be used to compare the result. For example to find all the people older than the ages 18 to 65 a <code>gtAll</code> query can be used:<p class="paragraph"/><div class="code"><pre>def results = Person.withCriteria &#123;
    gtAll <span class="java&#45;quote">"age"</span>, &#123;
        projections &#123;
            property <span class="java&#45;quote">"age"</span>
        &#125;
        between 'age', 18, 65
    &#125;<p class="paragraph"/>    order <span class="java&#45;quote">"firstName"</span>
&#125;</pre></div><p class="paragraph"/>The following table summarizes criteria methods for operating on subqueries that return multiple results:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Method</th><th>Description</th></tr><tr class="table-odd"><td><strong class="bold">gtAll</strong></td><td>greater than all subquery results</td></tr><tr class="table-even"><td><strong class="bold">geAll</strong></td><td>greater than or equal to all subquery results</td></tr><tr class="table-odd"><td><strong class="bold">ltAll</strong></td><td>less than all subquery results</td></tr><tr class="table-even"><td><strong class="bold">leAll</strong></td><td>less than or equal to all subquery results</td></tr><tr class="table-odd"><td><strong class="bold">eqAll</strong></td><td>equal to all subquery results</td></tr><tr class="table-even"><td><strong class="bold">neAll</strong></td><td>not equal to all subquery results</td></tr></table><p class="paragraph"/><h4>Batch Operations with Detached Criteria</h4><p class="paragraph"/>The <code>DetachedCriteria</code> class can be used to execute batch operations such as batch updates and deletes. For example, the following query will update all people with the surname "Simpson" to have the surname "Bloggs":<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
    eq 'lastName', 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = criteria.updateAll(lastName:<span class="java&#45;quote">"Bloggs"</span>)</pre></div><p class="paragraph"/><blockquote class="note">
Note that one limitation with regards to batch operations is that join queries (queries that query associations) are not allowed within the <code>DetachedCriteria</code> instance. 
</blockquote><p class="paragraph"/>To batch delete records you can use the <code>deleteAll</code> method:<p class="paragraph"/><div class="code"><pre>def criteria = <span class="java&#45;keyword">new</span> DetachedCriteria(Person).build &#123;
    eq 'lastName', 'Simpson'
&#125;
<span class="java&#45;object">int</span> total = criteria.deleteAll()</pre></div>


<a name="5.4.3 Hibernate Query Language (HQL)"><!-- Legacy link --></a>
<h2 id="hql">6.4.5 Hibernate Query Language (HQL)</h2>
GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/queryhql.html" target="blank">in the Hibernate documentation</a> of the Hibernate documentation.<p class="paragraph"/>GORM provides a number of methods that work with HQL including <a href="../ref/Domain Classes/find.html" class="domainClasses">find</a>, <a href="../ref/Domain Classes/findAll.html" class="domainClasses">findAll</a> and <a href="../ref/Domain Classes/executeQuery.html" class="domainClasses">executeQuery</a>. An example of a query can be seen below:<p class="paragraph"/><div class="code"><pre>def results =
      Book.findAll(<span class="java&#45;quote">"from Book as b where b.title like 'Lord of the%'"</span>)</pre></div><p class="paragraph"/><h4>Positional and Named Parameters</h4><p class="paragraph"/>In this case the value passed to the query is hard coded, however you can equally use positional parameters:<p class="paragraph"/><div class="code"><pre>def results =
      Book.findAll(<span class="java&#45;quote">"from Book as b where b.title like ?"</span>, &#91;<span class="java&#45;quote">"The Shi%"</span>&#93;)</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java&#45;quote">"Stephen King"</span>)
def books = Book.findAll(<span class="java&#45;quote">"from Book as book where book.author = ?"</span>,
                         &#91;author&#93;)</pre></div><p class="paragraph"/>Or even named parameters:<p class="paragraph"/><div class="code"><pre>def results =
      Book.findAll(<span class="java&#45;quote">"from Book as b "</span> +
                   <span class="java&#45;quote">"where b.title like :search or b.author like :search"</span>,
                   &#91;search: <span class="java&#45;quote">"The Shi%"</span>&#93;)</pre></div><p class="paragraph"/><div class="code"><pre>def author = Author.findByName(<span class="java&#45;quote">"Stephen King"</span>)
def books = Book.findAll(<span class="java&#45;quote">"from Book as book where book.author = :author"</span>,
                         &#91;author: author&#93;)</pre></div><p class="paragraph"/><h4>Multiline Queries</h4><p class="paragraph"/>Use the line continuation character to separate the query across multiple lines:<p class="paragraph"/><div class="code"><pre>def results = Book.findAll(<span class="java&#45;quote">"&#92;
from Book as b, &#92;
     Author as a &#92;
where b.author = a and a.surname = ?"</span>, &#91;'Smith'&#93;)</pre></div><p class="paragraph"/><blockquote class="note">
Triple-quoted Groovy multiline Strings will NOT work with HQL queries.
</blockquote><p class="paragraph"/><h4>Pagination and Sorting</h4><p class="paragraph"/>You can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination options as a Map at the end of the method call and include an "ORDER BY" clause in the HQL:<p class="paragraph"/><div class="code"><pre>def results =
      Book.findAll(<span class="java&#45;quote">"from Book as b where "</span> +
                   <span class="java&#45;quote">"b.title like 'Lord of the%' "</span> +
                   <span class="java&#45;quote">"order by b.title asc"</span>,
                   &#91;max: 10, offset: 20&#93;)</pre></div>


<a name="5.5 Advanced GORM Features"><!-- Legacy link --></a>
<h2 id="advancedGORMFeatures">6.5 Advanced GORM Features</h2>
The following sections cover more advanced usages of GORM including caching, custom mapping and events.

<a name="5.5.1 Events and Auto Timestamping"><!-- Legacy link --></a>
<h2 id="eventsAutoTimestamping">6.5.1 Events and Auto Timestamping</h2>
GORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events:
<ul class="star">
<li><code>beforeInsert</code> - Executed before an object is initially persisted to the database</li>
<li><code>beforeUpdate</code> - Executed before an object is updated</li>
<li><code>beforeDelete</code> - Executed before an object is deleted</li>
<li><code>beforeValidate</code> - Executed before an object is validated</li>
<li><code>afterInsert</code> - Executed after an object is persisted to the database</li>
<li><code>afterUpdate</code> - Executed after an object has been updated</li>
<li><code>afterDelete</code> - Executed after an object has been deleted</li>
<li><code>onLoad</code> - Executed when an object is loaded from the database</li>
</ul><p class="paragraph"/>To add an event simply register the relevant closure with your domain class.<p class="paragraph"/><blockquote class="warning">
Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events are fired during flushing this will cause a StackOverflowError.
</blockquote><p class="paragraph"/><h3>Event types</h3><p class="paragraph"/><h4>The beforeInsert event</h4><p class="paragraph"/>Fired before an object is saved to the database<p class="paragraph"/><div class="code"><pre>class Person &#123;
   <span class="java&#45;keyword">private</span> <span class="java&#45;keyword">static</span> <span class="java&#45;keyword">final</span> Date NULL_DATE = <span class="java&#45;keyword">new</span> Date(0)<p class="paragraph"/>   <span class="java&#45;object">String</span> firstName
   <span class="java&#45;object">String</span> lastName
   Date signupDate = NULL_DATE<p class="paragraph"/>   def beforeInsert() &#123;
      <span class="java&#45;keyword">if</span> (signupDate == NULL_DATE) &#123;
         signupDate = <span class="java&#45;keyword">new</span> Date()
      &#125;
   &#125;
&#125;</pre></div><p class="paragraph"/><h4>The beforeUpdate event</h4><p class="paragraph"/>Fired before an existing object is updated<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>   def securityService<p class="paragraph"/>   <span class="java&#45;object">String</span> firstName
   <span class="java&#45;object">String</span> lastName
   <span class="java&#45;object">String</span> lastUpdatedBy<p class="paragraph"/>   <span class="java&#45;keyword">static</span> constraints = &#123;
      lastUpdatedBy nullable: <span class="java&#45;keyword">true</span>
   &#125;<p class="paragraph"/>   def beforeUpdate() &#123;
      lastUpdatedBy = securityService.currentAuthenticatedUsername()
   &#125;
&#125;</pre></div><p class="paragraph"/><h4>The beforeDelete event</h4><p class="paragraph"/>Fired before an object is deleted.<p class="paragraph"/><div class="code"><pre>class Person &#123;
   <span class="java&#45;object">String</span> name<p class="paragraph"/>   def beforeDelete() &#123;
      ActivityTrace.withNewSession &#123;
         <span class="java&#45;keyword">new</span> ActivityTrace(eventName: <span class="java&#45;quote">"Person Deleted"</span>, data: name).save()
      &#125;
   &#125;
&#125;</pre></div><p class="paragraph"/>Notice the usage of <code>withNewSession</code> method above. Since events are triggered whilst Hibernate is flushing using persistence methods like <code>save()</code> and <code>delete()</code> won't result in objects being saved unless you run your operations with a new <code>Session</code>.<p class="paragraph"/>Fortunately the <code>withNewSession</code> method lets you share the same transactional JDBC connection even though you're using a different underlying <code>Session</code>.<p class="paragraph"/><h4>The beforeValidate event</h4><p class="paragraph"/>Fired before an object is validated.<p class="paragraph"/><div class="code"><pre>class Person &#123;
   <span class="java&#45;object">String</span> name<p class="paragraph"/>   <span class="java&#45;keyword">static</span> constraints = &#123;
       name size: 5..45
   &#125;<p class="paragraph"/>   def beforeValidate() &#123;
       name = name?.trim()
   &#125;
&#125;</pre></div><p class="paragraph"/>The <code>beforeValidate</code> method is run before any validators are run.<p class="paragraph"/><blockquote class="note">
Validation may run more often than you think. It is triggered by the <code>validate()</code> and <code>save()</code> methods as you'd expect, but it is also typically triggered just before the view is rendered as well. So when writing <code>beforeValidate()</code> implementations, make sure that they can handle being called multiple times with the same property values.
</blockquote><p class="paragraph"/>GORM supports an overloaded version of <code>beforeValidate</code> which accepts a <code>List</code> parameter which may include
the names of the properties which are about to be validated.  This version of <code>beforeValidate</code> will be called
when the <code>validate</code> method has been invoked and passed a <code>List</code> of property names as an argument.<p class="paragraph"/><div class="code"><pre>class Person &#123;
   <span class="java&#45;object">String</span> name
   <span class="java&#45;object">String</span> town
   <span class="java&#45;object">Integer</span> age<p class="paragraph"/>   <span class="java&#45;keyword">static</span> constraints = &#123;
       name size: 5..45
       age range: 4..99
   &#125;<p class="paragraph"/>   def beforeValidate(List propertiesBeingValidated) &#123;
      // <span class="java&#45;keyword">do</span> pre validation work based on propertiesBeingValidated
   &#125;
&#125;<p class="paragraph"/>def p = <span class="java&#45;keyword">new</span> Person(name: 'Jacob Brown', age: 10)
p.validate(&#91;'age', 'name'&#93;)</pre></div><p class="paragraph"/><blockquote class="note">
Note that when <code>validate</code> is triggered indirectly because of a call to the <code>save</code> method that
the <code>validate</code> method is being invoked with no arguments, not a <code>List</code> that includes all of
the property names.
</blockquote><p class="paragraph"/>Either or both versions of <code>beforeValidate</code> may be defined in a domain class.  GORM will
prefer the <code>List</code> version if a <code>List</code> is passed to <code>validate</code> but will fall back on the
no-arg version if the <code>List</code> version does not exist.  Likewise, GORM will prefer the
no-arg version if no arguments are passed to <code>validate</code> but will fall back on the
<code>List</code> version if the no-arg version does not exist.  In that case, <code>null</code> is passed to <code>beforeValidate</code>.<p class="paragraph"/><h4>The onLoad/beforeLoad event</h4><p class="paragraph"/>Fired immediately before an object is loaded from the database:<p class="paragraph"/><div class="code"><pre>class Person &#123;
   <span class="java&#45;object">String</span> name
   Date dateCreated
   Date lastUpdated<p class="paragraph"/>   def onLoad() &#123;
      log.debug <span class="java&#45;quote">"Loading &#36;&#123;id&#125;"</span>
   &#125;
&#125;</pre></div><p class="paragraph"/><code>beforeLoad()</code> is effectively a synonym for <code>onLoad()</code>, so only declare one or the other.<p class="paragraph"/><h4>The afterLoad event</h4><p class="paragraph"/>Fired immediately after an object is loaded from the database:<p class="paragraph"/><div class="code"><pre>class Person &#123;
   <span class="java&#45;object">String</span> name
   Date dateCreated
   Date lastUpdated<p class="paragraph"/>   def afterLoad() &#123;
      name = <span class="java&#45;quote">"I'm loaded"</span>
   &#125;
&#125;</pre></div><p class="paragraph"/><h4>Custom Event Listeners</h4><p class="paragraph"/>As of Grails 2.0 there is a new API for plugins and applications to register and listen for persistence events. This API is not tied to Hibernate and also works for other persistence plugins such as the <a href="http://grails.org/plugin/mongodb" target="blank">MongoDB plugin for GORM</a>.<p class="paragraph"/>To use this API you need to subclass <code>AbstractPersistenceEventListener</code> (in package  <em class="italic">org.grails.datastore.mapping.engine.event</em> ) and implement the methods <code>onPersistenceEvent</code> and <code>supportsEventType</code>. You also must provide a reference to the datastore to the listener.  The simplest possible implementation can be seen below:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">public</span> MyPersistenceListener(<span class="java&#45;keyword">final</span> Datastore datastore) &#123;
    <span class="java&#45;keyword">super</span>(datastore)
&#125;<p class="paragraph"/>@Override
<span class="java&#45;keyword">protected</span> void onPersistenceEvent(<span class="java&#45;keyword">final</span> AbstractPersistenceEvent event) &#123;
    <span class="java&#45;keyword">switch</span>(event.eventType) &#123;
        <span class="java&#45;keyword">case</span> PreInsert:
            println <span class="java&#45;quote">"PRE INSERT &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>
        <span class="java&#45;keyword">case</span> PostInsert:
            println <span class="java&#45;quote">"POST INSERT &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>
        <span class="java&#45;keyword">case</span> PreUpdate:
            println <span class="java&#45;quote">"PRE UPDATE &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>;
        <span class="java&#45;keyword">case</span> PostUpdate:
            println <span class="java&#45;quote">"POST UPDATE &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>;
        <span class="java&#45;keyword">case</span> PreDelete:
            println <span class="java&#45;quote">"PRE DELETE &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>;
        <span class="java&#45;keyword">case</span> PostDelete:
            println <span class="java&#45;quote">"POST DELETE &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>;
        <span class="java&#45;keyword">case</span> PreLoad:
            println <span class="java&#45;quote">"PRE LOAD &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>;
        <span class="java&#45;keyword">case</span> PostLoad:
            println <span class="java&#45;quote">"POST LOAD &#36;&#123;event.entityObject&#125;"</span>
        <span class="java&#45;keyword">break</span>;
    &#125;
&#125;<p class="paragraph"/>@Override
<span class="java&#45;keyword">public</span> <span class="java&#45;object">boolean</span> supportsEventType(<span class="java&#45;object">Class</span>&#60;? <span class="java&#45;keyword">extends</span> ApplicationEvent&#62; eventType) &#123;
    <span class="java&#45;keyword">return</span> <span class="java&#45;keyword">true</span>
&#125;</pre></div><p class="paragraph"/>The <code>AbstractPersistenceEvent</code> class has many subclasses (<code>PreInsertEvent</code>, <code>PostInsertEvent</code> etc.) that provide further information specific to the event. A <code>cancel()</code> method is also provided on the event which allows you to veto an insert, update or delete operation.<p class="paragraph"/>Once you have created your event listener you need to register it with the <code>ApplicationContext</code>. This can be done in <code>BootStrap.groovy</code>:<p class="paragraph"/><div class="code"><pre>def init = &#123;
    application.mainContext.eventTriggeringInterceptor.datastores.each &#123; k, datastore &#45;&#62;
        applicationContext.addApplicationListener <span class="java&#45;keyword">new</span> MyPersistenceListener(datastore)
    &#125;
&#125;</pre></div><p class="paragraph"/>or use this in a plugin:<p class="paragraph"/><div class="code"><pre>def doWithApplicationContext = &#123; applicationContext &#45;&#62;
    application.mainContext.eventTriggeringInterceptor.datastores.each &#123; k, datastore &#45;&#62;
        applicationContext.addApplicationListener <span class="java&#45;keyword">new</span> MyPersistenceListener(datastore)
    &#125;
&#125;</pre></div><p class="paragraph"/><h4>Hibernate Events</h4><p class="paragraph"/>It is generally encouraged to use the non-Hibernate specific API described above, but if you need access to more detailed Hibernate events then you can define custom Hibernate-specific event listeners.<p class="paragraph"/>You can also register event handler classes in an application's <code>grails-app/conf/spring/resources.groovy</code> or in the <code>doWithSpring</code> closure in a plugin descriptor by registering a Spring bean named <code>hibernateEventListeners</code>. This bean has one property, <code>listenerMap</code> which specifies the listeners to register for various Hibernate events.<p class="paragraph"/>The values of the Map are instances of classes that implement one or more Hibernate listener interfaces. You can use one class that implements all of the required interfaces, or one concrete class per interface, or any combination. The valid Map keys and corresponding interfaces are listed here:<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th><strong class="bold">Name</strong></th><th><strong class="bold">Interface</strong></th></tr><tr class="table-odd"><td>auto-flush</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/AutoFlushEventListener.html" class="api">AutoFlushEventListener</a></td></tr><tr class="table-even"><td>merge</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/MergeEventListener.html" class="api">MergeEventListener</a></td></tr><tr class="table-odd"><td>create</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PersistEventListener.html" class="api">PersistEventListener</a></td></tr><tr class="table-even"><td>create-onflush</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PersistEventListener.html" class="api">PersistEventListener</a></td></tr><tr class="table-odd"><td>delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/DeleteEventListener.html" class="api">DeleteEventListener</a></td></tr><tr class="table-even"><td>dirty-check</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/DirtyCheckEventListener.html" class="api">DirtyCheckEventListener</a></td></tr><tr class="table-odd"><td>evict</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/EvictEventListener.html" class="api">EvictEventListener</a></td></tr><tr class="table-even"><td>flush</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/FlushEventListener.html" class="api">FlushEventListener</a></td></tr><tr class="table-odd"><td>flush-entity</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/FlushEntityEventListener.html" class="api">FlushEntityEventListener</a></td></tr><tr class="table-even"><td>load</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/LoadEventListener.html" class="api">LoadEventListener</a></td></tr><tr class="table-odd"><td>load-collection</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/InitializeCollectionEventListener.html" class="api">InitializeCollectionEventListener</a></td></tr><tr class="table-even"><td>lock</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/LockEventListener.html" class="api">LockEventListener</a></td></tr><tr class="table-odd"><td>refresh</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/RefreshEventListener.html" class="api">RefreshEventListener</a></td></tr><tr class="table-even"><td>replicate</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/ReplicateEventListener.html" class="api">ReplicateEventListener</a></td></tr><tr class="table-odd"><td>save-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-even"><td>save</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-odd"><td>update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/SaveOrUpdateEventListener.html" class="api">SaveOrUpdateEventListener</a></td></tr><tr class="table-even"><td>pre-load</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreLoadEventListener.html" class="api">PreLoadEventListener</a></td></tr><tr class="table-odd"><td>pre-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreUpdateEventListener.html" class="api">PreUpdateEventListener</a></td></tr><tr class="table-even"><td>pre-delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreDeleteEventListener.html" class="api">PreDeleteEventListener</a></td></tr><tr class="table-odd"><td>pre-insert</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreInsertEventListener.html" class="api">PreInsertEventListener</a></td></tr><tr class="table-even"><td>pre-collection-recreate</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreCollectionRecreateEventListener.html" class="api">PreCollectionRecreateEventListener</a></td></tr><tr class="table-odd"><td>pre-collection-remove</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreCollectionRemoveEventListener.html" class="api">PreCollectionRemoveEventListener</a></td></tr><tr class="table-even"><td>pre-collection-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PreCollectionUpdateEventListener.html" class="api">PreCollectionUpdateEventListener</a></td></tr><tr class="table-odd"><td>post-load</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostLoadEventListener.html" class="api">PostLoadEventListener</a></td></tr><tr class="table-even"><td>post-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostUpdateEventListener.html" class="api">PostUpdateEventListener</a></td></tr><tr class="table-odd"><td>post-delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostDeleteEventListener.html" class="api">PostDeleteEventListener</a></td></tr><tr class="table-even"><td>post-insert</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostInsertEventListener.html" class="api">PostInsertEventListener</a></td></tr><tr class="table-odd"><td>post-commit-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostUpdateEventListener.html" class="api">PostUpdateEventListener</a></td></tr><tr class="table-even"><td>post-commit-delete</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostDeleteEventListener.html" class="api">PostDeleteEventListener</a></td></tr><tr class="table-odd"><td>post-commit-insert</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostInsertEventListener.html" class="api">PostInsertEventListener</a></td></tr><tr class="table-even"><td>post-collection-recreate</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostCollectionRecreateEventListener.html" class="api">PostCollectionRecreateEventListener</a></td></tr><tr class="table-odd"><td>post-collection-remove</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostCollectionRemoveEventListener.html" class="api">PostCollectionRemoveEventListener</a></td></tr><tr class="table-even"><td>post-collection-update</td><td><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/PostCollectionUpdateEventListener.html" class="api">PostCollectionUpdateEventListener</a></td></tr></table><p class="paragraph"/>For example, you could register a class <code>AuditEventListener</code> which implements <code>PostInsertEventListener</code>, <code>PostUpdateEventListener</code>, and <code>PostDeleteEventListener</code> using the following in an application:<p class="paragraph"/><div class="code"><pre>beans = &#123;<p class="paragraph"/>   auditListener(AuditEventListener)<p class="paragraph"/>   hibernateEventListeners(HibernateEventListeners) &#123;
      listenerMap = &#91;'post&#45;insert': auditListener,
                     'post&#45;update': auditListener,
                     'post&#45;delete': auditListener&#93;
   &#125;
&#125;</pre></div><p class="paragraph"/>or use this in a plugin:<p class="paragraph"/><div class="code"><pre>def doWithSpring = &#123;<p class="paragraph"/>   auditListener(AuditEventListener)<p class="paragraph"/>   hibernateEventListeners(HibernateEventListeners) &#123;
      listenerMap = &#91;'post&#45;insert': auditListener,
                     'post&#45;update': auditListener,
                     'post&#45;delete': auditListener&#93;
   &#125;
&#125;</pre></div><p class="paragraph"/><h4>Automatic timestamping</h4><p class="paragraph"/>If you define a <code>dateCreated</code> property it will be set to the current date for you when you create new instances. Likewise, if you define a <code>lastUpdated</code> property it will be automatically be updated for you when you change persistent instances.<p class="paragraph"/>If this is not the behaviour you want you can disable this feature with:<p class="paragraph"/><div class="code"><pre>class Person &#123;
   Date dateCreated
   Date lastUpdated
   <span class="java&#45;keyword">static</span> mapping = &#123;
      autoTimestamp <span class="java&#45;keyword">false</span>
   &#125;
&#125;</pre></div><p class="paragraph"/><blockquote class="warning">
If you have <code>nullable: false</code> constraints on either <code>dateCreated</code> or <code>lastUpdated</code>, your domain instances will fail validation - probably not what you want. Omit constraints from these properties unless you disable automatic timestamping.
</blockquote>


<a name="5.5.2 Custom ORM Mapping"><!-- Legacy link --></a>
<h2 id="ormdsl">6.5.2 Custom ORM Mapping</h2>
Grails domain classes can be mapped onto many legacy schemas with an Object Relational Mapping DSL (domain specific language). The following sections takes you through what is possible with the ORM DSL.<p class="paragraph"/><blockquote class="note">
None of this is necessary if you are happy to stick to the conventions defined by GORM for table names, column names and so on. You only needs this functionality if you need to tailor the way GORM maps onto legacy schemas or configures caching
</blockquote><p class="paragraph"/>Custom mappings are defined using a static <code>mapping</code> block defined within your domain class:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        version <span class="java&#45;keyword">false</span>
        autoTimestamp <span class="java&#45;keyword">false</span>
    &#125;
&#125;</pre></div><p class="paragraph"/>You can also configure global mappings in Config.groovy (or an external config file) using this setting:<p class="paragraph"/><div class="code"><pre>grails.gorm.<span class="java&#45;keyword">default</span>.mapping = &#123;
    version <span class="java&#45;keyword">false</span>
    autoTimestamp <span class="java&#45;keyword">false</span>
&#125;</pre></div><p class="paragraph"/>It has the same syntax as the standard <code>mapping</code> block but it applies to all your domain classes! You can then override these defaults within the <code>mapping</code> block of a domain class.

<a name="5.5.2.1 Table and Column Names"><!-- Legacy link --></a>
<h2 id="tableAndColumnNames">6.5.2.1 Table and Column Names</h2>
<h4>Table names</h4><p class="paragraph"/>The database table name which the class maps to can be customized using the <code>table</code> method:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
    &#125;
&#125;</pre></div><p class="paragraph"/>In this case the class would be mapped to a table called <code>people</code> instead of the default name of <code>person</code>.<p class="paragraph"/><h4>Column names</h4><p class="paragraph"/>It is also possible to customize the mapping for individual columns onto the database. For example to change the name you can do:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        firstName column: 'First_Name'
    &#125;
&#125;</pre></div><p class="paragraph"/>Here <code>firstName</code> is a dynamic method within the <code>mapping</code> Closure that has a single Map parameter. Since its name corresponds to a domain class persistent field, the parameter values (in this case just <code>"column"</code>) are used to configure the mapping for that property.<p class="paragraph"/><h4>Column type</h4><p class="paragraph"/>GORM supports configuration of Hibernate types with the DSL using the type attribute. This includes specifing user types that implement the Hibernate <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/usertype/UserType.html" class="api">org.hibernate.usertype.UserType</a> interface, which allows complete customization of how a type is persisted. As an example if you had a <code>PostCodeType</code> you could use it as follows:<p class="paragraph"/><div class="code"><pre>class Address &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> number
    <span class="java&#45;object">String</span> postCode<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        postCode type: PostCodeType
    &#125;
&#125;</pre></div><p class="paragraph"/>Alternatively if you just wanted to map it to one of Hibernate's basic types other than the default chosen by Grails you could use:<p class="paragraph"/><div class="code"><pre>class Address &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> number
    <span class="java&#45;object">String</span> postCode<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        postCode type: 'text'
    &#125;
&#125;</pre></div><p class="paragraph"/>This would make the <code>postCode</code> column map to the default large-text type for the database you're using (for example TEXT or CLOB).<p class="paragraph"/>See the Hibernate documentation regarding <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-types-basictypes" target="blank">Basic Types</a> for further information.<p class="paragraph"/><h4>Many-to-One/One-to-One Mappings</h4><p class="paragraph"/>In the case of associations it is also possible to configure the foreign keys used to map associations. In the case of a many-to-one or one-to-one association this is exactly the same as any regular column. For example consider the following:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName
    Address address<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        firstName column: 'First_Name'
        address column: 'Person_Address_Id'
    &#125;
&#125;</pre></div><p class="paragraph"/>By default the <code>address</code> association would map to a foreign key column called <code>address_id</code>. By using the above mapping we have changed the name of the foreign key column to <code>Person_Adress_Id</code>.<p class="paragraph"/><h4>One-to-Many Mapping</h4><p class="paragraph"/>With a bidirectional one-to-many you can change the foreign key column used by changing the column name on the many side of the association as per the example in the previous section on one-to-one associations. However, with unidirectional associations the foreign key needs to be specified on the association itself. For example given a unidirectional one-to-many relationship between <code>Person</code> and <code>Address</code> the following code will change the foreign key in the <code>address</code> table:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        firstName column: 'First_Name'
        addresses column: 'Person_Address_Id'
    &#125;
&#125;</pre></div><p class="paragraph"/>If you don't want the column to be in the <code>address</code> table, but instead some intermediate join table you can use the <code>joinTable</code> parameter:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        firstName column: 'First_Name'
        addresses joinTable: &#91;name: 'Person_Addresses',
                              key: 'Person_Id',
                              column: 'Address_Id'&#93;
    &#125;
&#125;</pre></div><p class="paragraph"/><h4>Many-to-Many Mapping</h4><p class="paragraph"/>Grails, by default maps a many-to-many association using a join table. For example consider this many-to-many association:<p class="paragraph"/><div class="code"><pre>class Group &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> hasMany = &#91;people: Person&#93;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> belongsTo = Group
    <span class="java&#45;keyword">static</span> hasMany = &#91;groups: Group&#93;
&#125;</pre></div><p class="paragraph"/>In this case Grails will create a join table called <code>group_person</code> containing foreign keys called <code>person_id</code> and <code>group_id</code> referencing the <code>person</code> and <code>group</code> tables. To change the column names you can specify a column within the mappings for each class.<p class="paragraph"/><div class="code"><pre>class Group &#123;
   &#8230;
   <span class="java&#45;keyword">static</span> mapping = &#123;
       people column: 'Group_Person_Id'
   &#125;
&#125;
class Person &#123;
   &#8230;
   <span class="java&#45;keyword">static</span> mapping = &#123;
       groups column: 'Group_Group_Id'
   &#125;
&#125;</pre></div><p class="paragraph"/>You can also specify the name of the join table to use:<p class="paragraph"/><div class="code"><pre>class Group &#123;
   &#8230;
   <span class="java&#45;keyword">static</span> mapping = &#123;
       people column: 'Group_Person_Id',
              joinTable: 'PERSON_GROUP_ASSOCIATIONS'
   &#125;
&#125;
class Person &#123;
   &#8230;
   <span class="java&#45;keyword">static</span> mapping = &#123;
       groups column: 'Group_Group_Id',
              joinTable: 'PERSON_GROUP_ASSOCIATIONS'
   &#125;
&#125;</pre></div>


<a name="5.5.2.2 Caching Strategy"><!-- Legacy link --></a>
<h2 id="caching">6.5.2.2 Caching Strategy</h2>
<h4>Setting up caching</h4><p class="paragraph"/><a href="http://www.hibernate.org/" target="blank">Hibernate</a> features a second-level cache with a customizable cache provider. This needs to be configured in the <code>grails-app/conf/DataSource.groovy</code> file as follows:<p class="paragraph"/><div class="code"><pre>hibernate &#123;
    cache.use_second_level_cache=<span class="java&#45;keyword">true</span>
    cache.use_query_cache=<span class="java&#45;keyword">true</span>
    cache.provider_class='org.hibernate.cache.EhCacheProvider'
&#125;</pre></div><p class="paragraph"/>You can customize any of these settings, for example to use a distributed caching mechanism.<p class="paragraph"/><blockquote class="note">
For further reading on caching and in particular Hibernate's second-level cache, refer to the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-cache" target="blank">Hibernate documentation</a> on the subject.
</blockquote><p class="paragraph"/><h4>Caching instances</h4><p class="paragraph"/>Call the <code>cache</code> method in your mapping block to enable caching with the default settings:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        cache <span class="java&#45;keyword">true</span>
    &#125;
&#125;</pre></div><p class="paragraph"/>This will configure a 'read-write' cache that includes both lazy and non-lazy properties. You can customize this further:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        cache usage: 'read&#45;only', include: 'non&#45;lazy'
    &#125;
&#125;</pre></div><p class="paragraph"/><h4>Caching associations</h4><p class="paragraph"/>As well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (associations) of objects. For example:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        version <span class="java&#45;keyword">false</span>
        addresses column: 'Address', cache: <span class="java&#45;keyword">true</span>
    &#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;
    <span class="java&#45;object">String</span> number
    <span class="java&#45;object">String</span> postCode
&#125;</pre></div><p class="paragraph"/>This will enable a 'read-write' caching mechanism on the <code>addresses</code> collection. You can also use:<p class="paragraph"/><div class="code"><pre>cache: 'read&#45;write' // or 'read&#45;only' or 'transactional'</pre></div><p class="paragraph"/>to further configure the cache usage.<p class="paragraph"/><h4>Caching Queries</h4><p class="paragraph"/>You can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the <code>cache</code> argument:<p class="paragraph"/><div class="code"><pre>def person = Person.findByFirstName(<span class="java&#45;quote">"Fred"</span>, &#91;cache: <span class="java&#45;keyword">true</span>&#93;)</pre></div><p class="paragraph"/><blockquote class="note">
In order for the results of the query to be cached, you must enable caching in your mapping as discussed in the previous section.
</blockquote><p class="paragraph"/>You can also cache criteria queries:<p class="paragraph"/><div class="code"><pre>def people = Person.withCriteria &#123;
    like('firstName', 'Fr%')
    cache <span class="java&#45;keyword">true</span>
&#125;</pre></div><p class="paragraph"/><h4>Cache usages</h4><p class="paragraph"/>Below is a description of the different cache settings and their usages:
<ul class="star">
<li><code>read-only</code> - If your application needs to read but never modify instances of a persistent class, a read-only cache may be used.</li>
<li><code>read-write</code> - If the application needs to update data, a read-write cache might be appropriate.</li>
<li><code>nonstrict-read-write</code> - If the application only occasionally needs to update data (ie. if it is very unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a <code>nonstrict-read-write</code> cache might be appropriate.</li>
<li><code>transactional</code> - The <code>transactional</code> cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify <code>hibernate.transaction.manager_lookup_class</code> in the <code>grails-app/conf/DataSource.groovy</code> file's <code>hibernate</code> config.</li>
</ul><p class="paragraph"/>

<a name="5.5.2.3 Inheritance Strategies"><!-- Legacy link --></a>
<h2 id="inheritanceStrategies">6.5.2.3 Inheritance Strategies</h2>
By default GORM classes use <code>table-per-hierarchy</code> inheritance mapping. This has the disadvantage that columns cannot have a <code>NOT-NULL</code> constraint applied to them at the database level. If you would prefer to use a <code>table-per-subclass</code> inheritance strategy you can do so as follows:<p class="paragraph"/><div class="code"><pre>class Payment &#123;
    <span class="java&#45;object">Integer</span> amount<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        tablePerHierarchy <span class="java&#45;keyword">false</span>
    &#125;
&#125;<p class="paragraph"/>class CreditCardPayment <span class="java&#45;keyword">extends</span> Payment &#123;
    <span class="java&#45;object">String</span> cardNumber
&#125;</pre></div><p class="paragraph"/>The mapping of the root <code>Payment</code> class specifies that it will not be using <code>table-per-hierarchy</code> mapping for all child classes.

<a name="5.5.2.4 Custom Database Identity"><!-- Legacy link --></a>
<h2 id="identity">6.5.2.4 Custom Database Identity</h2>
You can customize how GORM generates identifiers for the database using the DSL. By default GORM relies on the native database mechanism for generating ids. This is by far the best approach, but there are still many schemas that have different approaches to identity.<p class="paragraph"/>To deal with this Hibernate defines the concept of an id generator. You can customize the id generator and the column it maps to as follows:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        version <span class="java&#45;keyword">false</span>
        id generator: 'hilo',
           params: &#91;table: 'hi_value',
                    column: 'next_value',
                    max_lo: 100&#93;
    &#125;
&#125;</pre></div><p class="paragraph"/>In this case we're using one of Hibernate's built in 'hilo' generators that uses a separate table to generate ids.<p class="paragraph"/><blockquote class="note">
For more information on the different Hibernate generators refer to the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-declaration-id-generator" target="blank">Hibernate reference documentation</a>
</blockquote><p class="paragraph"/>Although you don't typically specify the <code>id</code> field (Grails adds it for you) you can still configure its mapping like the other properties. For example to customise the column for the id property you can do:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        version <span class="java&#45;keyword">false</span>
        id column: 'person_id'
    &#125;
&#125;</pre></div>


<a name="5.5.2.5 Composite Primary Keys"><!-- Legacy link --></a>
<h2 id="compositePrimaryKeys">6.5.2.5 Composite Primary Keys</h2>
GORM supports the concept of composite identifiers (identifiers composed from 2 or more properties). It is not an approach we recommend, but is available to you if you need it:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> org.apache.commons.lang.builder.HashCodeBuilder<p class="paragraph"/>class Person <span class="java&#45;keyword">implements</span> Serializable &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName
    <span class="java&#45;object">String</span> lastName<p class="paragraph"/>    <span class="java&#45;object">boolean</span> equals(other) &#123;
        <span class="java&#45;keyword">if</span> (!(other <span class="java&#45;keyword">instanceof</span> Person)) &#123;
            <span class="java&#45;keyword">return</span> <span class="java&#45;keyword">false</span>
        &#125;<p class="paragraph"/>        other.firstName == firstName &#38;&#38; other.lastName == lastName
    &#125;<p class="paragraph"/>    <span class="java&#45;object">int</span> hashCode() &#123;
        def builder = <span class="java&#45;keyword">new</span> HashCodeBuilder()
        builder.append firstName
        builder.append lastName
        builder.toHashCode()
    &#125;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        id composite: &#91;'firstName', 'lastName'&#93;
    &#125;
&#125;</pre></div><p class="paragraph"/>The above will create a composite id of the <code>firstName</code> and <code>lastName</code> properties of the Person class. To retrieve an instance by id you use a prototype of the object itself:<p class="paragraph"/><div class="code"><pre>def p = Person.get(<span class="java&#45;keyword">new</span> Person(firstName: <span class="java&#45;quote">"Fred"</span>, lastName: <span class="java&#45;quote">"Flintstone"</span>))
println p.firstName</pre></div><p class="paragraph"/>Domain classes mapped with composite primary keys must implement the <code>Serializable</code> interface and override the <code>equals</code> and <code>hashCode</code> methods, using the properties in the composite key for the calculations. The example above uses a <code>HashCodeBuilder</code> for convenience but it's fine to implement it yourself.<p class="paragraph"/>Another important consideration when using composite primary keys is associations. If for example you have a many-to-one association where the foreign keys are stored in the associated table then 2 columns will be present in the associated table.<p class="paragraph"/>For example consider the following domain class:<p class="paragraph"/><div class="code"><pre>class Address &#123;
    Person person
&#125;</pre></div><p class="paragraph"/>In this case the <code>address</code> table will have an additional two columns called <code>person_first_name</code> and <code>person_last_name</code>. If you wish the change the mapping of these columns then you can do so using the following technique:<p class="paragraph"/><div class="code"><pre>class Address &#123;
    Person person
    <span class="java&#45;keyword">static</span> mapping = &#123;
        person &#123;
            column: <span class="java&#45;quote">"FirstName"</span>
            column: <span class="java&#45;quote">"LastName"</span>
        &#125;
    &#125;
&#125;</pre></div>


<a name="5.5.2.6 Database Indices"><!-- Legacy link --></a>
<h2 id="databaseIndices">6.5.2.6 Database Indices</h2>
To get the best performance out of your queries it is often necessary to tailor the table index definitions. How you tailor them is domain specific and a matter of monitoring usage patterns of your queries. With GORM's DSL you can specify which columns are used in which indexes:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    <span class="java&#45;object">String</span> firstName
    <span class="java&#45;object">String</span> address
    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        version <span class="java&#45;keyword">false</span>
        id column: 'person_id'
        firstName column: 'First_Name', index: 'Name_Idx'
        address column: 'Address', index: 'Name_Idx,Address_Index'
    &#125;
&#125;</pre></div><p class="paragraph"/>Note that you cannot have any spaces in the value of the <code>index</code> attribute; in this example <code>index:'Name_Idx, Address_Index'</code> will cause an error.


<a name="5.5.2.7 Optimistic Locking and Versioning"><!-- Legacy link --></a>
<h2 id="optimisticLockingAndVersioning">6.5.2.7 Optimistic Locking and Versioning</h2>
As discussed in the section on <a href="../guide/single.html#locking" class="guide">Optimistic and Pessimistic Locking</a>, by default GORM uses optimistic locking and automatically injects a <code>version</code> property into every class which is in turn mapped to a <code>version</code> column at the database level.<p class="paragraph"/>If you're mapping to a legacy schema that doesn't have version columns (or there's some other reason why you don't want/need this feature) you can disable this with the <code>version</code> method:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
        version <span class="java&#45;keyword">false</span>
    &#125;
&#125;</pre></div><p class="paragraph"/><blockquote class="note">
If you disable optimistic locking you are essentially on your own with regards to concurrent updates and are open to the risk of users losing data (due to data overriding) unless you use <a href="../guide/single.html#locking" class="guide">pessimistic locking</a>
</blockquote><p class="paragraph"/><h4>Version columns types</h4><p class="paragraph"/>By default Grails maps the <code>version</code> property as a <code>Long</code> that gets incremented by one each time an instance is updated. But Hibernate also supports using a <code>Timestamp</code>, for example:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">import</span> java.sql.Timestamp<p class="paragraph"/>class Person &#123;<p class="paragraph"/>    &#8230;
    Timestamp version<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        table 'people'
    &#125;
&#125;</pre></div><p class="paragraph"/>There's a slight risk that two updates occurring at nearly the same time on a fast server can end up with the same timestamp value but this risk is very low. One benefit of using a <code>Timestamp</code> instead of a <code>Long</code> is that you combine the optimistic locking and last-updated semantics into a single column.


<a name="5.5.2.8 Eager and Lazy Fetching"><!-- Legacy link --></a>
<h2 id="fetchingDSL">6.5.2.8 Eager and Lazy Fetching</h2>
<h4>Lazy Collections</h4><p class="paragraph"/>As discussed in the section on <a href="../guide/single.html#fetching" class="guide">Eager and Lazy fetching</a>, GORM collections are lazily loaded by default but you can change this behaviour with the ORM DSL. There are several options available to you, but the most common ones are:
<ul class="star">
<li>lazy: false</li>
<li>fetch: 'join'</li>
</ul><p class="paragraph"/>and they're used like this:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName
    Pet pet<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        addresses lazy: <span class="java&#45;keyword">false</span>
        pet fetch: 'join'
    &#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;
    <span class="java&#45;object">String</span> street
    <span class="java&#45;object">String</span> postCode
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Pet &#123;
    <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/>The first option, <code>lazy: false</code> , ensures that when a <code>Person</code> instance is loaded, its <code>addresses</code> collection is loaded at the same time with a second SELECT. The second option is basically the same, except the collection is loaded with a JOIN rather than another SELECT. Typically you want to reduce the number of queries, so <code>fetch: 'join'</code> is the more appropriate option. On the other hand, it could feasibly be the more expensive approach if your domain model and data result in more and larger results than would otherwise be necessary.<p class="paragraph"/>For more advanced users, the other settings available are:
<ol>
<li>batchSize: N</li>
<li>lazy: false, batchSize: N</li>
</ol><p class="paragraph"/>where N is an integer. These let you fetch results in batches, with one query per batch. As a simple example, consider this mapping for <code>Person</code>:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName
    Pet pet<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        pet batchSize: 5
    &#125;
&#125;</pre></div>
If a query returns multiple <code>Person</code> instances, then when we access the first <code>pet</code> property, Hibernate will fetch that <code>Pet</code> plus the four next ones. You can get the same behaviour with eager loading by combining <code>batchSize</code> with the <code>lazy: false</code> option. You can find out more about these options in the <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-fetching" target="blank">Hibernate user guide</a> and this <a href="http://community.jboss.org/wiki/AShortPrimerOnFetchingStrategies" target="blank">primer on fetching strategies</a>. Note that ORM DSL does not currently support the "subselect" fetching strategy.<p class="paragraph"/><h4>Lazy Single-Ended Associations</h4><p class="paragraph"/>In GORM, one-to-one and many-to-one associations are by default lazy. Non-lazy single ended associations can be problematic when you load many entities because each non-lazy association will result in an extra SELECT statement. If the associated entities also have non-lazy associations, the number of queries grows significantly!<p class="paragraph"/>Use the same technique as for lazy collections to make a one-to-one or many-to-one association non-lazy/eager:<p class="paragraph"/><div class="code"><pre>class Person &#123;
    <span class="java&#45;object">String</span> firstName
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> street
    <span class="java&#45;object">String</span> postCode<p class="paragraph"/>    <span class="java&#45;keyword">static</span> belongsTo = &#91;person: Person&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        person lazy: <span class="java&#45;keyword">false</span>
    &#125;
&#125;</pre></div><p class="paragraph"/>Here we configure GORM to load the associated <code>Person</code> instance (through the <code>person</code> property) whenever an <code>Address</code> is loaded.<p class="paragraph"/><h4>Lazy Single-Ended Associations and Proxies</h4><p class="paragraph"/>Hibernate uses runtime-generated proxies to facilitate single-ended lazy associations; Hibernate dynamically subclasses the entity class to create the proxy.<p class="paragraph"/>Consider the previous example but with a lazily-loaded <code>person</code> association: Hibernate will set the <code>person</code> property to a proxy that is a subclass of <code>Person</code>. When you call any of the getters (except for the <code>id</code> property) or setters on that proxy, Hibernate will load the entity from the database.<p class="paragraph"/>Unfortunately this technique can produce surprising results. Consider the following example classes:<p class="paragraph"/><div class="code"><pre>class Pet &#123;
    <span class="java&#45;object">String</span> name
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Dog <span class="java&#45;keyword">extends</span> Pet &#123;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Person &#123;
    <span class="java&#45;object">String</span> name
    Pet pet
&#125;</pre></div><p class="paragraph"/>and assume that we have a single <code>Person</code> instance with a <code>Dog</code> as the <code>pet</code>. The following code will work as you would expect:
<div class="code"><pre>def person = Person.get(1)
assert person.pet <span class="java&#45;keyword">instanceof</span> Dog
assert Pet.get(person.petId) <span class="java&#45;keyword">instanceof</span> Dog</pre></div><p class="paragraph"/>But this won't:<p class="paragraph"/><div class="code"><pre>def person = Person.get(1)
assert person.pet <span class="java&#45;keyword">instanceof</span> Dog
assert Pet.list()&#91;0&#93; <span class="java&#45;keyword">instanceof</span> Dog</pre></div><p class="paragraph"/>The second assertion fails, and to add to the confusion, this will work:<p class="paragraph"/><div class="code"><pre>assert Pet.list()&#91;0&#93; <span class="java&#45;keyword">instanceof</span> Dog</pre></div><p class="paragraph"/>What's going on here? It's down to a combination of how proxies work and the guarantees that the Hibernate session makes. When you load the <code>Person</code> instance, Hibernate creates a proxy for its <code>pet</code> relation and attaches it to the session. Once that happens, whenever you retrieve that <code>Pet</code> instance with a query, a <code>get()</code>, or the <code>pet</code> relation  <em class="italic">within the same session</em>  , Hibernate gives you the proxy.<p class="paragraph"/>Fortunately for us, GORM automatically unwraps the proxy when you use <code>get()</code> and <code>findBy&#42;()</code>, or when you directly access the relation. That means you don't have to worry at all about proxies in the majority of cases. But GORM doesn't do that for objects returned with a query that returns a list, such as <code>list()</code> and <code>findAllBy&#42;()</code>. However, if Hibernate hasn't attached the proxy to the session, those queries will return the real instances - hence why the last example works.<p class="paragraph"/>You can protect yourself to a degree from this problem by using the <code>instanceOf</code> method by GORM:<p class="paragraph"/><div class="code"><pre>def person = Person.get(1)
assert Pet.list()&#91;0&#93;.instanceOf(Dog)</pre></div><p class="paragraph"/>However, it won't help here if casting is involved. For example, the following code will throw a <code>ClassCastException</code> because the first pet in the list is a proxy instance with a class that is neither <code>Dog</code> nor a sub-class of <code>Dog</code>:<p class="paragraph"/><div class="code"><pre>def person = Person.get(1)
Dog pet = Pet.list()&#91;0&#93;</pre></div><p class="paragraph"/>Of course, it's best not to use static types in this situation. If you use an untyped variable for the pet instead, you can access any <code>Dog</code> properties or methods on the instance without any problems.<p class="paragraph"/>These days it's rare that you will come across this issue, but it's best to be aware of it just in case. At least you will know why such an error occurs and be able to work around it.


<a name="5.5.2.9 Custom Cascade Behaviour"><!-- Legacy link --></a>
<h2 id="customCascadeBehaviour">6.5.2.9 Custom Cascade Behaviour</h2>
As described in the section on <a href="../guide/single.html#cascades" class="guide">cascading updates</a>, the primary mechanism to control the way updates and deletes cascade from one association to another is the static <a href="../ref/Domain Classes/belongsTo.html" class="domainClasses">belongsTo</a> property.<p class="paragraph"/>However, the ORM DSL gives you complete access to Hibernate's <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html#objectstate-transitive" target="blank">transitive persistence</a> capabilities using the <code>cascade</code> attribute.<p class="paragraph"/>Valid settings for the cascade attribute include:
<ul class="star">
<li><code>merge</code> - merges the state of a detached association</li>
<li><code>save-update</code> - cascades only saves and updates to an association</li>
<li><code>delete</code> - cascades only deletes to an association</li>
<li><code>lock</code> - useful if a pessimistic lock should be cascaded to its associations</li>
<li><code>refresh</code> - cascades refreshes to an association</li>
<li><code>evict</code> - cascades evictions (equivalent to <code>discard()</code> in GORM) to associations if set</li>
<li><code>all</code> - cascade  <em class="italic">all</em>  operations to associations</li>
<li><code>all-delete-orphan</code> - Applies only to one-to-many associations and indicates that when a child is removed from an association then it should be automatically deleted. Children are also deleted when the parent is.</li>
</ul><p class="paragraph"/><blockquote class="note">
It is advisable to read the section in the Hibernate documentation on <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html#objectstate-transitive" target="blank">transitive persistence</a> to obtain a better understanding of the different cascade styles and recommendations for their usage
</blockquote><p class="paragraph"/>To specify the cascade attribute simply define one or more (comma-separated) of the aforementioned settings as its value:<p class="paragraph"/><div class="code"><pre>class Person &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> firstName<p class="paragraph"/>    <span class="java&#45;keyword">static</span> hasMany = &#91;addresses: Address&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        addresses cascade: <span class="java&#45;quote">"all&#45;delete&#45;orphan"</span>
    &#125;
&#125;</pre></div><p class="paragraph"/><div class="code"><pre>class Address &#123;
    <span class="java&#45;object">String</span> street
    <span class="java&#45;object">String</span> postCode
&#125;</pre></div>


<a name="5.5.2.10 Custom Hibernate Types"><!-- Legacy link --></a>
<h2 id="customHibernateTypes">6.5.2.10 Custom Hibernate Types</h2>
You saw in an earlier section that you can use composition (with the <code>embedded</code> property) to break a table into multiple objects. You can achieve a similar effect with Hibernate's custom user types. These are not domain classes themselves, but plain Java or Groovy classes. Each of these types also has a corresponding "meta-type" class that implements <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/usertype/UserType.html" class="api">org.hibernate.usertype.UserType</a>.<p class="paragraph"/>The <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-types-custom" target="blank">Hibernate reference manual</a> has some information on custom types, but here we will focus on how to map them in Grails. Let's start by taking a look at a simple domain class that uses an old-fashioned (pre-Java 1.5) type-safe enum class:<p class="paragraph"/><div class="code"><pre>class Book &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> title
    <span class="java&#45;object">String</span> author
    Rating rating<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        rating type: RatingUserType
    &#125;
&#125;</pre></div><p class="paragraph"/>All we have done is declare the <code>rating</code> field the enum type and set the property's type in the custom mapping to the corresponding <code>UserType</code> implementation. That's all you have to do to start using your custom type. If you want, you can also use the other column settings such as "column" to change the column name and "index" to add it to an index.<p class="paragraph"/>Custom types aren't limited to just a single column - they can be mapped to as many columns as you want. In such cases you explicitly define in the mapping what columns to use, since Hibernate can only use the property name for a single column. Fortunately, Grails lets you map multiple columns to a property using this syntax:<p class="paragraph"/><div class="code"><pre>class Book &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> title
    Name author
    Rating rating<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        name type: NameUserType, &#123;
            column name: <span class="java&#45;quote">"first_name"</span>
            column name: <span class="java&#45;quote">"last_name"</span>
        &#125;
        rating type: RatingUserType
    &#125;
&#125;</pre></div><p class="paragraph"/>The above example will create "first_name" and "last_name" columns for the <code>author</code> property. You'll be pleased to know that you can also use some of the normal column/property mapping attributes in the column definitions. For example:<p class="paragraph"/><div class="code"><pre>column name: <span class="java&#45;quote">"first_name"</span>, index: <span class="java&#45;quote">"my_idx"</span>, unique: <span class="java&#45;keyword">true</span></pre></div><p class="paragraph"/>The column definitions do  <em class="italic">not</em>  support the following attributes: <code>type</code>, <code>cascade</code>, <code>lazy</code>, <code>cache</code>, and <code>joinTable</code>.<p class="paragraph"/>One thing to bear in mind with custom types is that they define the  <em class="italic">SQL types</em>  for the corresponding database columns. That helps take the burden of configuring them yourself, but what happens if you have a legacy database that uses a different SQL type for one of the columns? In that case, override the column's SQL type using the <code>sqlType</code> attribute:<p class="paragraph"/><div class="code"><pre>class Book &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> title
    Name author
    Rating rating<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        name type: NameUserType, &#123;
            column name: <span class="java&#45;quote">"first_name"</span>, sqlType: <span class="java&#45;quote">"text"</span>
            column name: <span class="java&#45;quote">"last_name"</span>, sqlType: <span class="java&#45;quote">"text"</span>
        &#125;
        rating type: RatingUserType, sqlType: <span class="java&#45;quote">"text"</span>
    &#125;
&#125;</pre></div><p class="paragraph"/>Mind you, the SQL type you specify needs to still work with the custom type. So overriding a default of "varchar" with "text" is fine, but overriding "text" with "yes_no" isn't going to work.


<a name="5.5.2.11 Derived Properties"><!-- Legacy link --></a>
<h2 id="derivedProperties">6.5.2.11 Derived Properties</h2>
A derived property is one that takes its value from a SQL expression, often but not necessarily based on the value of one or more other persistent properties.  Consider a Product class like this:<p class="paragraph"/><div class="code"><pre>class Product &#123;
    <span class="java&#45;object">Float</span> price
    <span class="java&#45;object">Float</span> taxRate
    <span class="java&#45;object">Float</span> tax
&#125;</pre></div><p class="paragraph"/>If the <code>tax</code> property is derived based on the value of <code>price</code> and <code>taxRate</code> properties then is probably no need to persist the <code>tax</code> property.  The SQL used to derive the value of a derived property may be expressed in the ORM DSL like this:<p class="paragraph"/><div class="code"><pre>class Product &#123;
    <span class="java&#45;object">Float</span> price
    <span class="java&#45;object">Float</span> taxRate
    <span class="java&#45;object">Float</span> tax<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        tax formula: 'PRICE &#42; TAX_RATE'
    &#125;
&#125;</pre></div><p class="paragraph"/>Note that the formula expressed in the ORM DSL is SQL so references to other properties should relate to the persistence model not the object model, which is why the example refers to <code>PRICE</code> and <code>TAX_RATE</code> instead of <code>price</code> and <code>taxRate</code>.<p class="paragraph"/>With that in place, when a Product is retrieved with something like <code>Product.get(42)</code>, the SQL that is generated to support that will look something like this:<p class="paragraph"/><div class="code"><pre>select
    product0_.id as id1_0_,
    product0_.version as version1_0_,
    product0_.price as price1_0_,
    product0_.tax_rate as tax4_1_0_,
    product0_.PRICE &#42; product0_.TAX_RATE as formula1_0_
from
    product product0_
where
    product0_.id=?</pre></div><p class="paragraph"/>Since the <code>tax</code> property is derived at runtime and not stored in the database it might seem that the same effect could be achieved by adding a method like <code>getTax()</code> to the <code>Product</code> class that simply returns the product of the <code>taxRate</code> and <code>price</code> properties.  With an approach like that you would give up the ability query the database based on the value of the <code>tax</code> property.  Using a derived property allows exactly that.  To retrieve all <code>Product</code> objects that have a <code>tax</code> value greater than 21.12 you could execute a query like this:<p class="paragraph"/><div class="code"><pre>Product.findAllByTaxGreaterThan(21.12)</pre></div><p class="paragraph"/>Derived properties may be referenced in the Criteria API:<p class="paragraph"/><div class="code"><pre>Product.withCriteria &#123;
    gt 'tax', 21.12f
&#125;</pre></div><p class="paragraph"/>The SQL that is generated to support either of those would look something like this:<p class="paragraph"/><div class="code"><pre>select
    this_.id as id1_0_,
    this_.version as version1_0_,
    this_.price as price1_0_,
    this_.tax_rate as tax4_1_0_,
    this_.PRICE &#42; this_.TAX_RATE as formula1_0_
from
    product this_
where
    this_.PRICE &#42; this_.TAX_RATE&#62;?</pre></div><p class="paragraph"/><blockquote class="note">
Because the value of a derived property is generated in the database and depends on the execution of SQL code, derived properties may not have GORM constraints applied to them.  If constraints are specified for a derived property, they will be ignored.
</blockquote>


<a name="5.5.2.12 Custom Naming Strategy"><!-- Legacy link --></a>
<h2 id="customNamingStrategy">6.5.2.12 Custom Naming Strategy</h2>
By default Grails uses Hibernate's <code>ImprovedNamingStrategy</code> to convert domain class Class and field names to SQL table and column names by converting from camel-cased Strings to ones that use underscores as word separators. You can customize these on a per-class basis in the <code>mapping</code> closure but if there's a consistent pattern you can specify a different <code>NamingStrategy</code> class to use.<p class="paragraph"/>Configure the class name to be used in <code>grails-app/conf/DataSource.groovy</code> in the <code>hibernate</code> section, e.g.<p class="paragraph"/><div class="code"><pre>dataSource &#123;
    pooled = <span class="java&#45;keyword">true</span>
    dbCreate = <span class="java&#45;quote">"create&#45;drop"</span>
    &#8230;
&#125;<p class="paragraph"/>hibernate &#123;
    cache.use_second_level_cache = <span class="java&#45;keyword">true</span>
    &#8230;
    naming_strategy = com.myco.myproj.CustomNamingStrategy
&#125;</pre></div><p class="paragraph"/>You can also specify the name of the class and it will be loaded for you:<p class="paragraph"/><div class="code"><pre>hibernate &#123;
    &#8230;
    naming_strategy = 'com.myco.myproj.CustomNamingStrategy'
&#125;</pre></div><p class="paragraph"/>A third option is to provide an instance if there is some configuration required beyond calling the default constructor:<p class="paragraph"/><div class="code"><pre>hibernate &#123;
    &#8230;
    def strategy = <span class="java&#45;keyword">new</span> com.myco.myproj.CustomNamingStrategy()
    // configure as needed
    naming_strategy = strategy
&#125;</pre></div><p class="paragraph"/>You can use an existing class or write your own, for example one that prefixes table names and column names:<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">package</span> com.myco.myproj<p class="paragraph"/><span class="java&#45;keyword">import</span> org.hibernate.cfg.ImprovedNamingStrategy
<span class="java&#45;keyword">import</span> org.hibernate.util.StringHelper<p class="paragraph"/>class CustomNamingStrategy <span class="java&#45;keyword">extends</span> ImprovedNamingStrategy &#123;<p class="paragraph"/>    <span class="java&#45;object">String</span> classToTableName(<span class="java&#45;object">String</span> className) &#123;
        <span class="java&#45;quote">"table_"</span> + StringHelper.unqualify(className)
    &#125;<p class="paragraph"/>    <span class="java&#45;object">String</span> propertyToColumnName(<span class="java&#45;object">String</span> propertyName) &#123;
        <span class="java&#45;quote">"col_"</span> + StringHelper.unqualify(propertyName)
    &#125;
&#125;</pre></div><p class="paragraph"/>

<a name="5.5.3 Default Sort Order"><!-- Legacy link --></a>
<h2 id="defaultSortOrder">6.5.3 Default Sort Order</h2>
You can sort objects using query arguments such as those found in the <a href="../ref/Domain Classes/list.html" class="domainClasses">list</a> method:<p class="paragraph"/><div class="code"><pre>def airports = Airport.list(sort:'name')</pre></div><p class="paragraph"/>However, you can also declare the default sort order for a collection in the mapping:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        sort <span class="java&#45;quote">"name"</span>
    &#125;
&#125;</pre></div><p class="paragraph"/>The above means that all collections of <code>Airport</code> instances will by default be sorted by the airport name. If you also want to change the sort  <em class="italic">order</em> , use this syntax:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> mapping = &#123;
        sort name: <span class="java&#45;quote">"desc"</span>
    &#125;
&#125;</pre></div><p class="paragraph"/>Finally, you can configure sorting at the association level:<p class="paragraph"/><div class="code"><pre>class Airport &#123;
    &#8230;
    <span class="java&#45;keyword">static</span> hasMany = &#91;flights: Flight&#93;<p class="paragraph"/>    <span class="java&#45;keyword">static</span> mapping = &#123;
        flights sort: 'number', order: 'desc'
    &#125;
&#125;</pre></div><p class="paragraph"/>In this case, the <code>flights</code> collection will always be sorted in descending order of flight number.<p class="paragraph"/><blockquote class="warning">
These mappings will not work for default unidirectional one-to-many or many-to-many relationships because they involve a join table. See <a href="http://jira.codehaus.org/browse/GRAILS-4089" target="blank">this issue</a> for more details. Consider using a <code>SortedSet</code> or queries with sort parameters to fetch the data you need.
</blockquote>


<a name="5.6 Programmatic Transactions"><!-- Legacy link --></a>
<h2 id="programmaticTransactions">6.6 Programmatic Transactions</h2>
Grails is built on Spring and uses Spring's Transaction abstraction for dealing with programmatic transactions. However, GORM classes have been enhanced to make this simpler with the <a href="../ref/Domain Classes/withTransaction.html" class="domainClasses">withTransaction</a> method. This method has a single parameter, a Closure, which has a single parameter which is a Spring <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/TransactionStatus.html" class="api">TransactionStatus</a> instance.<p class="paragraph"/>Here's an example of using <code>withTransaction</code> in a controller methods:<p class="paragraph"/><div class="code"><pre>def transferFunds() &#123;
    Account.withTransaction &#123; status &#45;&#62;
        def source = Account.get(params.from)
        def dest = Account.get(params.to)<p class="paragraph"/>        def amount = params.amount.toInteger()
        <span class="java&#45;keyword">if</span> (source.active) &#123;
            <span class="java&#45;keyword">if</span> (dest.active) &#123;
                source.balance &#45;= amount
                dest.amount += amount
            &#125;
            <span class="java&#45;keyword">else</span> &#123;
                status.setRollbackOnly()
            &#125;
        &#125;
    &#125;
&#125;</pre></div><p class="paragraph"/>In this example we rollback the transaction if the destination account is not active. Also, if an unchecked <code>Exception</code> or <code>Error</code> (but not a checked <code>Exception</code>, even though Groovy doesn't require that you catch checked exceptions) is thrown during the process the transaction will automatically be rolled back.<p class="paragraph"/>You can also use "save points" to rollback a transaction to a particular point in time if you don't want to rollback the entire transaction. This can be achieved through the use of Spring's <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/SavepointManager.html" class="api">SavePointManager</a> interface.<p class="paragraph"/>The <code>withTransaction</code> method deals with the begin/commit/rollback logic for you within the scope of the block.


<a name="5.7 GORM and Constraints"><!-- Legacy link --></a>
<h2 id="gormConstraints">6.7 GORM and Constraints</h2>
Although constraints are covered in the <a href="../guide/single.html#constraints" class="guide">Validation</a> section, it is important to mention them here as some of the constraints can affect the way in which the database schema is generated.<p class="paragraph"/>Where feasible, Grails uses a domain class's constraints to influence the database columns generated for the corresponding domain class properties.<p class="paragraph"/>Consider the following example.  Suppose we have a domain model with the following properties:<p class="paragraph"/><div class="code"><pre><span class="java&#45;object">String</span> name
<span class="java&#45;object">String</span> description</pre></div><p class="paragraph"/>By default, in MySQL, Grails would define these columns as<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Column</th><th>Data Type</th></tr><tr class="table-odd"><td>name</td><td>varchar(255)</td></tr><tr class="table-even"><td>description</td><td>varchar(255)</td></tr></table><p class="paragraph"/>But perhaps the business rules for this domain class state that a description can be up to 1000 characters in length.  If that were the case, we would likely define the column as follows  <em class="italic">if</em>  we were creating the table with an SQL script.<p class="paragraph"/><table class="wiki-table" cellpadding="0" cellspacing="0" border="0"><tr><th>Column</th><th>Data Type</th></tr><tr class="table-odd"><td>description</td><td>TEXT</td></tr></table><p class="paragraph"/>Chances are we would also want to have some application-based validation to make sure we don't exceed that 1000 character limit  <em class="italic">before</em>  we persist any records.  In Grails, we achieve this validation with <a href="../guide/single.html#constraints" class="guide">constraints</a>.  We would add the following constraint declaration to the domain class.<p class="paragraph"/><div class="code"><pre><span class="java&#45;keyword">static</span> constraints = &#123;
    description maxSize: 1000
&#125;</pre></div><p class="paragraph"/>This constraint would provide both the application-based validation we want and it would also cause the schema to be generated as shown above.  Below is a description of the other constraints that influence schema generation.<p class="paragraph"/><h4>Constraints Affecting String Properties</h4>
<ul class="star">
<li><a href="../ref/Constraints/inList.html" class="constraints">inList</a></li>
<li><a href="../ref/Constraints/maxSize.html" class="constraints">maxSize</a></li>
<li><a href="../ref/Constraints/size.html" class="constraints">size</a></li>
</ul><p class="paragraph"/>If either the <code>maxSize</code> or the <code>size</code> constraint is defined, Grails sets the maximum column length based on the constraint value.<p class="paragraph"/>In general, it's not advisable to use both constraints on the same domain class property.  However, if both the <code>maxSize</code> constraint and the <code>size</code> constraint are defined, then Grails sets the column length to the minimum of the <code>maxSize</code> constraint and the upper bound of the size constraint.  (Grails uses the minimum of the two, because any length that exceeds that minimum will result in a validation error.)<p class="paragraph"/>If the <code>inList</code> constraint is defined (and the <code>maxSize</code> and the <code>size</code> constraints are not defined), then Grails sets the maximum column length based on the length of the longest string in the list of valid values.  For example, given a list including values "Java", "Groovy", and "C++", Grails would set the column length to 6 (i.e., the number of characters in the string "Groovy").<p class="paragraph"/><h4>Constraints Affecting Numeric Properties</h4>
<ul class="star">
<li><a href="../ref/Constraints/min.html" class="constraints">min</a></li>
<li><a href="../ref/Constraints/max.html" class="constraints">max</a></li>
<li><a href="../ref/Constraints/range.html" class="constraints">range</a></li>
</ul><p class="paragraph"/>If the <code>max</code>, <code>min</code>, or <code>range</code> constraint is defined, Grails attempts to set the column precision based on the constraint value.  (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)<p class="paragraph"/>In general, it's not advisable to combine the pair <code>min</code>/<code>max</code> and <code>range</code> constraints together on the same domain class property.  However, if both of these constraints is defined, then Grails uses the minimum precision value from the constraints.  (Grails uses the minimum of the two, because any length that exceeds that minimum precision will result in a validation error.)
<ul class="star">
<li><a href="../ref/Constraints/scale.html" class="constraints">scale</a></li>
</ul><p class="paragraph"/>If the scale constraint is defined, then Grails attempts to set the column <a href="../ref/Constraints/scale.html" class="constraints">scale</a> based on the constraint value.  This rule only applies to floating point numbers (i.e., <code>java.lang.Float</code>, <code>java.Lang.Double</code>, <code>java.lang.BigDecimal</code>, or subclasses of <code>java.lang.BigDecimal</code>). The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.<p class="paragraph"/>The constraints define the minimum/maximum numeric values, and Grails derives the maximum number of digits for use in the precision. Keep in mind that specifying only one of <code>min</code>/<code>max</code> constraints will not affect schema generation (since there could be large negative value of property with max:100, for example), unless the specified constraint value requires more digits than default Hibernate column precision is (19 at the moment). For example:<p class="paragraph"/><div class="code"><pre>someFloatValue max: 1000000, scale: 3</pre></div><p class="paragraph"/>would yield:<p class="paragraph"/><div class="code"><pre>someFloatValue DECIMAL(19, 3) // precision is <span class="java&#45;keyword">default</span></pre></div><p class="paragraph"/>but<p class="paragraph"/><div class="code"><pre>someFloatValue max: 12345678901234567890, scale: 5</pre></div><p class="paragraph"/>would yield:
<div class="code"><pre>someFloatValue DECIMAL(25, 5) // precision = digits in max + scale</pre></div><p class="paragraph"/>and<p class="paragraph"/><div class="code"><pre>someFloatValue max: 100, min: &#45;100000</pre></div><p class="paragraph"/>would yield:<p class="paragraph"/><div class="code"><pre>someFloatValue DECIMAL(8, 2) // precision = digits in min + <span class="java&#45;keyword">default</span> scale</pre></div>



                <div style="clear:both;margin-top:15px;"></div>
                
                    <div class="toc-item prev-left"><a href="../guide/commandLine.html">&lt;&lt; <strong>5</strong><span>The Command Line</span></a></div>
                
                    <div class="toc-item next-right"><a href="../guide/theWebLayer.html"><strong>7</strong><span>The Web Layer</span> >></a></div>
                
                <div style="clear:both"></div>
            </div>
        </td>
        <td id="col2">
            <div class="local clearfix">
                <div class="local-title">
                    <a href="../guide/index.html" target="mainFrame">Quick Reference</a>
                    <span class="toggle">(<a href="#" onclick="localToggle(); return false;">hide</a>)</span>
                </div>
                <div class="menu">
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Command Line</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Command%20Line/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/add-proxy.html">add-proxy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/alias.html">alias</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/bootstrap.html">bootstrap</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/bug-report.html">bug-report</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/clean.html">clean</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/clear-proxy.html">clear-proxy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/compile.html">compile</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/console.html">console</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-app.html">create-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-controller.html">create-controller</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-domain-class.html">create-domain-class</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-filters.html">create-filters</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-hibernate-cfg-xml.html">create-hibernate-cfg-xml</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-integration-test.html">create-integration-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-multi-project-build.html">create-multi-project-build</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-plugin.html">create-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-pom.html">create-pom</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-scaffold-controller.html">create-scaffold-controller</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-script.html">create-script</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-service.html">create-service</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-tag-lib.html">create-tag-lib</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/create-unit-test.html">create-unit-test</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/dependency-report.html">dependency-report</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/doc.html">doc</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-all.html">generate-all</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-controller.html">generate-controller</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/generate-views.html">generate-views</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/help.html">help</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/init.html">init</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/install-dependency.html">install-dependency</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/install-plugin.html">install-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/install-templates.html">install-templates</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/integrate-with.html">integrate-with</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/interactive.html">interactive</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/list-plugin-updates.html">list-plugin-updates</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/list-plugins.html">list-plugins</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/migrate-docs.html">migrate-docs</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/package-plugin.html">package-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/package.html">package</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/plugin-info.html">plugin-info</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/refresh-dependencies.html">refresh-dependencies</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/remove-proxy.html">remove-proxy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-app.html">run-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-script.html">run-script</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/run-war.html">run-war</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/schema-export.html">schema-export</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/set-proxy.html">set-proxy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/set-version.html">set-version</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/shell.html">shell</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/stats.html">stats</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/stop-app.html">stop-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/test-app.html">test-app</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/uninstall-plugin.html">uninstall-plugin</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/upgrade.html">upgrade</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/war.html">war</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Command%20Line/wrapper.html">wrapper</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Constraints</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Constraints/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Constraints/attributes.html">attributes</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/bindable.html">bindable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/blank.html">blank</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/creditCard.html">creditCard</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/email.html">email</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/inList.html">inList</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/matches.html">matches</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/max.html">max</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/maxSize.html">maxSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/min.html">min</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/minSize.html">minSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/notEqual.html">notEqual</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/nullable.html">nullable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/range.html">range</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/scale.html">scale</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/size.html">size</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/unique.html">unique</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/url.html">url</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/validator.html">validator</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Constraints/widget.html">widget</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Controllers</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Controllers/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Controllers/actionName.html">actionName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/afterInterceptor.html">afterInterceptor</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/allowedMethods.html">allowedMethods</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/beforeInterceptor.html">beforeInterceptor</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/bindData.html">bindData</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/chain.html">chain</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/controllerName.html">controllerName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/defaultAction.html">defaultAction</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/flash.html">flash</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/forward.html">forward</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/grailsApplication.html">grailsApplication</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/params.html">params</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/redirect.html">redirect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/render.html">render</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/session.html">session</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/withForm.html">withForm</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Controllers/withFormat.html">withFormat</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Database Mapping</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Database%20Mapping/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/autoImport.html">autoImport</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/autoTimestamp.html">autoTimestamp</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/batchSize.html">batchSize</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/cache.html">cache</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/cascade.html">cascade</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/column.html">column</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/comment.html">comment</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/discriminator.html">discriminator</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicInsert.html">dynamicInsert</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/dynamicUpdate.html">dynamicUpdate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/fetch.html">fetch</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/id.html">id</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/ignoreNotFound.html">ignoreNotFound</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/indexColumn.html">indexColumn</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/insertable.html">insertable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/joinTable.html">joinTable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/lazy.html">lazy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/order.html">order</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/sort.html">sort</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/table.html">table</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/type.html">type</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/updateable.html">updateable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Database%20Mapping/version.html">version</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Domain Classes</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Domain%20Classes/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/addTo.html">addTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/attach.html">attach</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/belongsTo.html">belongsTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/clearErrors.html">clearErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/constraints.html">constraints</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/count.html">count</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/countBy.html">countBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/createCriteria.html">createCriteria</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/delete.html">delete</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/discard.html">discard</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/embedded.html">embedded</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/errors.html">errors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/executeQuery.html">executeQuery</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/executeUpdate.html">executeUpdate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/exists.html">exists</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/fetchMode.html">fetchMode</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/find.html">find</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAll.html">findAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAllBy.html">findAllBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findAllWhere.html">findAllWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findBy.html">findBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateBy.html">findOrCreateBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrCreateWhere.html">findOrCreateWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveBy.html">findOrSaveBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findOrSaveWhere.html">findOrSaveWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/findWhere.html">findWhere</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/first.html">first</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/get.html">get</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getAll.html">getAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getDirtyPropertyNames.html">getDirtyPropertyNames</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/getPersistentValue.html">getPersistentValue</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasMany.html">hasMany</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/hasOne.html">hasOne</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/ident.html">ident</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/instanceOf.html">instanceOf</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/isAttached.html">isAttached</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/isDirty.html">isDirty</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/last.html">last</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/list.html">list</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/listOrderBy.html">listOrderBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/load.html">load</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/lock.html">lock</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mappedBy.html">mappedBy</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/mapping.html">mapping</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/merge.html">merge</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/namedQueries.html">namedQueries</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/properties.html">properties</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/read.html">read</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/refresh.html">refresh</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/removeFrom.html">removeFrom</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/save.html">save</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/transients.html">transients</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/validate.html">validate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/where.html">where</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/whereAny.html">whereAny</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withCriteria.html">withCriteria</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withNewSession.html">withNewSession</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withSession.html">withSession</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Domain%20Classes/withTransaction.html">withTransaction</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Plug-ins</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Plug-ins/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/URL%20mappings.html">URL mappings</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/codecs.html">codecs</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/controllers.html">controllers</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/core.html">core</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/dataSource.html">dataSource</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/domainClasses.html">domainClasses</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/filters.html">filters</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/hibernate.html">hibernate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/i18n.html">i18n</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/logging.html">logging</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/scaffolding.html">scaffolding</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/services.html">services</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/servlets.html">servlets</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Plug-ins/web%20flow.html">web flow</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Services</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Services/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Services/scope.html">scope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Services/transactional.html">transactional</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Servlet API</h1><div class="menu-sub">
                        
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Servlet%20API/session.html">session</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tag Libraries</h1><div class="menu-sub">
                        
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/Usage.html">Usage</a></div>
                            
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/actionName.html">actionName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/controllerName.html">controllerName</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/flash.html">flash</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/pageScope.html">pageScope</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/params.html">params</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/request.html">request</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/response.html">response</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/servletContext.html">servletContext</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tag%20Libraries/session.html">session</a>
                            </div>
                            
                            </div>
                    </div>
                    
                    <div class="menu-block"><h1 class="menu-title" onclick="toggleRef(this.parentNode.childNodes[1])">Tags</h1><div class="menu-sub">
                        
                            
                            <div class="menu-item"><a href="../ref/Tags/actionSubmit.html">actionSubmit</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/actionSubmitImage.html">actionSubmitImage</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/applyLayout.html">applyLayout</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/checkBox.html">checkBox</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/collect.html">collect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/cookie.html">cookie</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/country.html">country</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/countrySelect.html">countrySelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/createLink.html">createLink</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/createLinkTo.html">createLinkTo</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/currencySelect.html">currencySelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/datePicker.html">datePicker</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/each.html">each</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/eachError.html">eachError</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/else.html">else</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/elseif.html">elseif</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/external.html">external</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/field.html">field</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/fieldValue.html">fieldValue</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/findAll.html">findAll</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/form.html">form</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formRemote.html">formRemote</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatBoolean.html">formatBoolean</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatDate.html">formatDate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/formatNumber.html">formatNumber</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/grep.html">grep</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/hasErrors.html">hasErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/header.html">header</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/hiddenField.html">hiddenField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/if.html">if</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/img.html">img</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/include.html">include</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/isAvailable.html">isAvailable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/isNotAvailable.html">isNotAvailable</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/javascript.html">javascript</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/join.html">join</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutBody.html">layoutBody</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutHead.html">layoutHead</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/layoutTitle.html">layoutTitle</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/link.html">link</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/localeSelect.html">localeSelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/message.html">message</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/meta.html">meta</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/pageProperty.html">pageProperty</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/paginate.html">paginate</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/passwordField.html">passwordField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/radio.html">radio</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/radioGroup.html">radioGroup</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/remoteField.html">remoteField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/remoteFunction.html">remoteFunction</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/remoteLink.html">remoteLink</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/render.html">render</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/renderErrors.html">renderErrors</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/resource.html">resource</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/select.html">select</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/set.html">set</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/setProvider.html">setProvider</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/sortableColumn.html">sortableColumn</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/submitButton.html">submitButton</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/submitToRemote.html">submitToRemote</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/textArea.html">textArea</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/textField.html">textField</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/timeZoneSelect.html">timeZoneSelect</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/unless.html">unless</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/uploadForm.html">uploadForm</a>
                            </div>
                            
                            <div class="menu-item"><a href="../ref/Tags/while.html">while</a>
                            </div>
                            
                            </div>
                    </div>
                    
                </div>
            </div>
        </td>
    </tr>
</table>

<div id="footer">
    Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
    Sponsored by <a href="http://springsource.com">SpringSource</a>
</div>

<script type="text/javascript" src="../js/docs.js"></script>

</body>
</html>
